How can I access @public NSArray or NSMutableArray after updating it? From one class to another?
I can access it with calling -(id)init.. when program starts, but if I want to update it later, I get nil. What’s the problem?
Simple example code:
MyFirstClass.h
#import <Foundation/Foundation.h>
@interface MyFirstClass : NSObject
{
@public
NSArray *testArray;
}
-(IBAction)Button:(id)sender;
@end
MyFirstClass.m
#import "MyFirstClass.h"
@implementation MyFirstClass
- (id)init {
if (self = [super init]) {
//I can take this Array from here
//testArray = [NSArray arrayWithObjects: @"first", @"second", @"third", nil];
}
return self;
}
-(IBAction)Button:(id)sender {
//How take this Array?
testArray = [NSArray arrayWithObjects: @"first", @"second", @"third", nil];
}
@end
SimpleClass.h
#import <Foundation/Foundation.h>
#import "MyFirstClass.h"
@interface SimpleClass : NSObject
{
MyFirstClass *other;
}
-(IBAction)ButtonGet:(id)sender;
@end
SimpleClass.m
#import "SimpleClass.h"
#import "MyFirstClass.h"
@implementation SimpleClass
-(IBAction)ButtonGet:(id)sender {
other = [[MyFirstClass alloc] init];
if(other->testArray) {
NSLog(@"Working!");
}
else { NSLog(@"Not working!"); }
}
@end
Created example has two buttons in *.xib. One button named “Button” (MyFirstClass) and other “ButtonGet” (SimpleClass). So when program starts need to push “Button” and then “ButtonGet”, after that NSLog should write “Working!” if it gets testArray and if not – “Not working!”. It always shows “Not Working!”.
Welcome to Objective C! If you feel overwhelmed, and would like to read some introductory material, please have a look at the links in Peter Hosey’s excellent “Useful Cocoa/Cocoa Touch Links” card.
You create the
MyFirstClassinstance in-[SimpleClass ButtonGet:], and since itstestArraymember isn’t explicitly assigned to in-[MyFirstClass init], it is (correctly) initialized to nil. It will remain that way forever unless you assign something else to it, but you never do. (You only assign to it in[MyFirstClass Button:], but you never call that method.)Other things to consider:
Manual memory management requires that you know the Cocoa memory management rules and constantly keep them in mind while writing your code. For example, you need to retain the result of
+[NSArray arrayWithObjects:]when you assign it to a member variable, and release it in-[MyFirstClass dealloc]. Similarly, you need to release theotherobject in-[SimpleClass dealloc].It is much cleaner to use properties (declared using
@property) instead of directly referring to another class’s member variables.Please consider following the Cocoa Coding Guidelines and starting your method names with a lowercase letter. It makes your code fit better with the system APIs, and makes it much easier to read for other people.