2013-07-05 108 views
0

我刚刚使用Xcode的工具将项目从MRR移动到ARC。我有这样的例程:ARC在方法中创建新对象

@interface myObject 
{ 
    NSMutableArray* __strong myItems; 
} 
@property NSMutableArray* myItems; 
- (BOOL) readLegacyFormatItems; 
@end 



- (BOOL) readLegacyFormatItems 
{ 
    NSMutableArray* localCopyOfMyItems = [[NSMutableArray alloc]init]; 
    //create objects and store them to localCopyOfMyItems 

    [self setMyItems: localCopyOfMyItems] 

    return TRUE; 
} 

这在MRR下工作正常,但在ARC下,myItems会立即发布。我该如何解决这个问题?

我已阅读关于__strong和__weak引用,但我还没有看到如何在这种情况下应用它们。

非常感谢所有的信息!

回答

1

这应该工作,因为它是。但是你不需要再申报iVars。只需使用属性。你甚至不需要综合它们。强大的属性将保留任何指定的对象,弱的属性不会。

此外,类名应始终为大写。而且 - 既然你存储了一个可变数组,你也可以将你的对象直接添加到属性中。不需要另一个局部可变数组变量。

@interface MyObject 
@property (nonatomic, strong) NSMutableArray *myItems; 
- (BOOL)readLegacyFormatItems; 
@end 


@implementation MyObject 

- (BOOL) readLegacyFormatItems 
{ 
    self.myItems = [[NSMutableArray alloc]init]; 

    //create objects and store them directly to self.myItems 

    return TRUE; 
} 

@end 
+0

感谢您的信息。那么也许我犯的错误就是我首先创建MyObject的方式。当一个特定的菜单项被点击时,我有一个IBAction。它看起来像这样: (IBAction)importLegacyItems:(id)sender {myObject * newInstanceOfmyObject; newInstanceOfmyObject = [[myObject alloc] init]; [newInstanceOfmyObject \t \t \t readLegacyFormatItems]; } 我必须做一些事情来保持newInstanceOfmyObject在这个例程结束时被释放吗? – VikR

+0

奇怪的是,我无法在这里更好地格式化! – VikR

+0

我想我可能已经找到了它 - 我需要通过windowcontroller创建对象。例如theWindowController = [[NSWindowController alloc] initWithWindowNibName:@“MyObject”myObject]; – VikR