2014-10-27 31 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