do I need to manually create a NSMutableArray if it is already covered by a property & synthesize method? (code attached)
Do I need to manually create a NSMutableArray if it is already covered by a property & synthesize method?
In the code below I'm seeing an issue whereby the "addEvent" method doesn't seem to be working. Even after calling it the count for the _events variable is still zero (0). I'm wondering in this code whether the issue might be that I need to manually create/initialise the Array? (and not rely on the sythesize method doing this)
Header File
#import <Foundation/Foundation.h>
@interface Weekend : NSObject {
NSMutableArray* _events;
}
- (void)addEvent:(EKEvent*)event;
@property (nonatomic, retain) NSMutableArray* events;
@end
Implementation
#import "Weekend.h"
@implementation Weekend
@synthesize events = _events;
- (void)addEvent:(EKEvent*)event {
[self.events addObjec开发者_如何学Pythont:event];
}
@end
Yes.
The @synthesize
automatically creates the getter/setter methods that are used when you refer to self.events
. It does not allocate (or release) the _events object for you.
You can create it in the init method, but if you want to get a little fancier, you can also override the getter method like this:
-(NSMutableArray *)events
{
if (_events == nil) {
_events = [[NSMutableArray alloc] init];
}
return _events;
}
If you do it this way instead of in your init method, then your variables only get initilized when they're actually needed, which can be handy in some cases.
Remember that you still need to release in the dealloc method.
you need to allocate the memory first .
The problem is you need to allocate memory to your array ..
_events=[[NSMutableArray alloc]init]; & then add objects to this array.
& also don't forget to release this array at appropriate place , otherwise will create lot of crashing issue.
_events = nil; [_events release];
If you want to access the getter & setter properties then & then only do
@property (nonatomic, retain) NSMutableArray* events; & synthesize the array otherwise simply it will work for you.
精彩评论