2014-10-27 76 views
0

我有我的AppDelegate类似的代码:目标C复制属性VS副本消息

@interface AppDelegate() 
{} 
@property(nonatomic, assign) UILocalNotification* mSavedLocalNotification; 
@property(nonatomic, assign) UILocalNotification* tmpNotification1; 
@property(nonatomic, copy) UILocalNotification* tmpNotification2; 
@end 



@implementation AppDelegate 
@synthesize mSavedLocalNotification=mSavedLocalNotification; 
@synthesize tmpNotification1=tmpNotification1; 
@synthesize tmpNotification2=tmpNotification2; 



- (BOOL)application:(UIApplication *) __unused application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions 
    { 
      UILocalNotification* notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 
      if (notification) 
      { 
       mSavedLocalNotification = [notification copy]; 
       tmpNotification1 = notification; 
       tmpNotification2 = notification; 

       NSLog(@"########## %p %p %p %p", mSavedLocalNotification, notification, tmpNotification1, tmpNotification2); 
      } 
    } 

从我的理解通过阅读教程,在属性复制属性应该做的是调用拷贝方法同样的事情确实。

那么,为什么这个程序的打印:0x15d39270 0x15dcc0d0 0x15dcc0d0 0x15dcc0d0 ?

为什么具有复制属性tmpNotification2 = notification;酒店仅保持相同的指针,而不是克隆它,而mSavedLocalNotification = [notification copy];实际上创造了一个新的。

回答

1

“复制”方法不会复制不可变项目。由于它们是不可改变的,不能改变,所以复制是没有意义的。

但更糟的是,你显然使用实例变量。您似乎忽略了实例变量应以下划线字符开头的编码约定;你实际上是在积极规避它。这就是为什么你访问成员变量的错误并不明显。

+0

+1因此,解决方案是删除'@ synthesize'行,让Xcode完成工作。 – trojanfoe 2014-10-27 10:47:18

+0

在我删除了@synthesize部分(我首先添加的,因为其他选项不起作用)并使用self.mSavedLocalNotification = notification(而不是_mSavedLocalNotification = notification)之后,copy属性完成了我期望的操作。我只复制了一个不可变的对象,因为有一个强引用之前没有工作(从同样的原因复制不起作用)。 – Gabi 2014-10-27 11:15:38