add objects to NSMutableArray when defined in .h
I am testing NSMutableArray and do not understand what i am doing wrong.
When i define "myArray" locally the [myArray addObject:@"First line"]; works but if i define it in the .h file it ends up as null.
开发者_运维百科I am using myArray to add the text of multiple selected cell's in a UITableView "didSelectRowAtIndexPath".
Could someone nice explain what i am doing wrong?
Make sure you have it like this in your .h file:
@interface YourViewController : UIViewController {
NSMutableArray *myArray;
}
@property(nonatomic, retain) NSMutableArray *myArray;
@end
And in your .m file
@implementation YourViewController
@synthesize myArray
//make sure you release it
- (void)dealloc {
[myArray release];
}
/*....other code..... */
/*make sure it's initialised somewhere */
- (void)viewDidLoad {
[super viewDidLoad];
myArray = [[NSMutableArray] alloc] init];
}
@end
Are you just declaring an NSMutableArray in the header file? If so, it still needs to be initialized somewhere in the .m file. You could do this like so:
array = [[NSMutableArray alloc] init];
[array addObject:@"First line"];
In .h file
NSMutableArray *myArray;
In .m file
-(void)viewDidLoad
{
[super viewDidLoad];
myArray = [[NSMutableArray] alloc] init];
[myArray addObject:@"myObject"];
}
精彩评论