Thursday, 22 August 2013

Prevent class from being allocated in iOS

Prevent class from being allocated in iOS

I'm wondering how it is possible to create a class in Objective-C that
cannot be allocated (or init)?
I'm trying to replicate the SKDownload Apple class (StoreKit framework)
and I noticed that the documentation doesn't mention any alloc or init
methods. This may be missing in the documentation but present in the code
? (some .h declaration missing to prevent us from using this method?).
I've tried to +alloc-init this class and either alloc and init return
null.
What I'm trying to achieve is a class B that possesses only getters, that
can only be created by a class A (just like factory methods would do -
only A can create and return B instances, but the user cannot create B
directly).
Example:
@interface A : NSObject
// Only A "+createB" class method can create B instances
+ (Second *)createBWithValue:(int)value;
@end
@interface B : NSObject
- (id)init; // return nil
+ (id)alloc; // return nil
- (int)value; // this returns the value passed from A
@end
Question 1: How would you proceed to create such classes? Is is possible ?
Question 2: How can - (int)value on B return the value passed in the class
method in A? (knowing that +alloc, -init and/or other memory allocation
methods may be nullified since users cannot create B classes directly -
also custom initWithValue methods in B may be unavailable too)
I'm a little confused on how the Apple engineers do that..are there hidden
methods that Apple doesn't want me to use?
Thanks you.

No comments:

Post a Comment