Search code examples
iosobjective-carraysstatic

Static variable is nil - Objective-C


I am doing some Objective-C exercises. I have two classes here one "main class" and one "sub class". What I needed is to get all the instances of my "main class" and put it in an array. I also wanted to use it in my "subclass". Below I give a small example.

@interface mainClass : NSObject
static NSArray *instanceObj;
@end
@implementation mainClass

//Here I used the designated initializer to initialize and add the instance to the     Array
@end


@interface subClass:mainClass
@end
@implementation subClass

//Here I want to use the Array to get instances of mainClass.
@end

If I do as the above example, I get a warning stating that the static array is not used and when getting data from Array it's nil. Also I tried declaring the static array in implementation file of "main Class", but I cannot use the Array in "Sub Class". Kindly provide me a solution and help me understand the concept.


Solution

  • A couple of issues:

    1. Move the static outside of the @interface, and into the .m file above the @implementation.

    2. You obviously would need to make that NSMutableArray, not an NSArray.

    3. Be forewarned that by adding objects to that array, that establishes a strong reference to those objects, and they won't be released until you remove them from the array.

    As an aside, you might also want to conform to Cocoa naming conventions, using MainClass and SubClass rather than mainClass and subClass. Better, use meaningful names.