简体   繁体   English

如果属性和synthesize方法已包含NSMutableArray,我是否需要手动创建它? (附加代码)

[英]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? 如果属性和synthesize方法已包含NSMutableArray,我是否需要手动创建它?

In the code below I'm seeing an issue whereby the "addEvent" method doesn't seem to be working. 在下面的代码中,我看到了一个问题,即“ addEvent”方法似乎不起作用。 Even after calling it the count for the _events variable is still zero (0). 即使调用它,_events变量的计数仍为零(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) (而不是依靠sythesize方法执行此操作)

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 addObject:event];
}

@end

Yes. 是。

The @synthesize automatically creates the getter/setter methods that are used when you refer to self.events . @synthesize自动创建在引用self.events时使用的getter / setter方法。 It does not allocate (or release) the _events object for you. 它不会为您分配(或释放)_events对象。

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: 您可以在init方法中创建它,但是如果您想稍微想一点,还可以重写getter方法,如下所示:

-(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. 如果以这种方式而不是在init方法中执行此操作,则变量仅在实际需要时才被初始化,这在某些情况下会很方便。

Remember that you still need to release in the dealloc method. 请记住,您仍然需要在dealloc方法中释放。

您需要先分配内存。

The problem is you need to allocate memory to your array .. 问题是您需要为数组分配内存。

_events=[[NSMutableArray alloc]init]; _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 = nil; [_events release]; [_events版本];

If you want to access the getter & setter properties then & then only do 如果要访问getter和setter属性,则&然后仅执行

@property (nonatomic, retain) NSMutableArray* events; @property(非原子,保留)NSMutableArray *事件; & synthesize the array otherwise simply it will work for you. &合成数组,否则简单地它将为您工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM