2010-02-24 60 views
2

我在應用程序中遇到了NSString問題。
我已經在我的視圖控制器的頭文件中定義了它。iPhone應用程序在訪問NSString時隨機退出

NSString *locationCoordinates; 

我在 - (void)方法中設置它的值。

- (void)locationUpdate:(CLLocation *)location { 
    <...> 

    NSArray *locArray = [locString componentsSeparatedByString:@", "]; 

    NSString *xCoordinate = [locArray objectAtIndex:0]; 
    NSString *yCoordinate = [locArray objectAtIndex:1]; 

    locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate]; 
} 

在這種方法中,我可以

NSLog(locationCoordinates); 

它打印到控制檯,但如果我想在另一種方法控制檯來查看它,我的應用程序立即退出。

- (IBAction)saveAndReturnToRootView { 
    NSLog(locationCoordinates); 
} 

控制檯告訴我:

2010-02-24 14:45:05.399 MyApp[73365:207] *** -[NSCFSet length]: unrecognized selector sent to instance 0x4c36490 
2010-02-24 14:45:05.400 MyApp[73365:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFSet length]: unrecognized selector sent to instance 0x4c36490' 
2010-02-24 14:45:05.401 MyApp[73365:207] Stack: (
    32887899, 
    2434934025, 
    33269819, 
    32839286, 
    32691906, 
    32417461, 
    32527181, 
    32527085, 
    32747749, 
    356942, 
    630491, 
    63461, 
    2868313, 
    4782069, 
    2868313, 
    3275682, 
    3284419, 
    3279631, 
    2973235, 
    2881564, 
    2908341, 
    40984273, 
    32672640, 
    32668744, 
    40978317, 
    40978514, 
    2912259, 
    9744, 
    9598 
) 

我怎樣才能解決這個問題?

在此先感謝;-)

回答

7

您的arent固定字符串,所以內存正在被清理。當您嘗試訪問它時會導致崩潰。

要保留它,你可以添加以下行

[locationCoordinates retain]; 

記住釋放它,當你不再需要它 - 很可能在你的類的析構函數,否則你將有一個內存泄漏。


目標C中的標準做法是對這些類成員使用屬性。在頭文件中使用

@property (nonatomic, retain) NSString *locationCoordinates; 

然後在實現卡盤的

@synthesize locationCoordinates; 

當您訪問locationCoordinates訪問它通過自我爲:

self.locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate]; 

目標C將創建一個getter和二傳手財產,將以最有效的方式處理您的保留。

順便說一句,非原子屬性中的關鍵字告訴目標c,你不需要它創建圍繞屬性訪問的任何線程同步。如果你將要多線程課程,你應該考慮刪除nonatomic。這將確保屬性訪問是線程安全的。

沒有意義的工作,你可以讓編譯器爲你做!

+1

@property的+1 – willcodejavaforfood 2010-02-24 14:59:17

+0

好的,太棒了,謝謝! – iYassin 2010-02-24 15:27:40

+0

真棒,樂意幫忙!我最終設法讓我的頭腦圍繞Objective C的內存管理,足以回答一個關於它的問題。它是一個漫長的旅程..! ;-) – 2010-02-24 16:06:47

5

在類的變量存儲時,你應該保留字符串:

locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate]; 
[locationCoordinates retain]; 

的原因是,[的NSString stringWithFormat:...]返回自動釋放實例。該函數結束時,字符串將自動釋放。

你也可以複製字符串:

locationCoordinates = 
    [[NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate] copy]; 

,當然還有,別忘了在的dealloc再次釋放:

- (void) dealloc { 
    [locationCoordinates release]; 

    [super dealloc]; 
} 
+0

如果您使用此方法而不是屬性,則需要在爲您指定一個新值之前向locationCoordinates發送一條發佈消息,否則如果locationUpdate:被多次調用,則會泄漏內存。 – 2010-02-24 15:22:19

+0

非常有用,非常感謝! – iYassin 2010-02-24 15:25:17