2012-04-28 45 views
0

我得到在4小時內瘋狂,我真的需要幫助剛開EXC_BAD_ACCESS。下面是代碼:同時使用的NSString

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    //check if strGroup has prefix and suffix # 
    BOOL result; 

    result = [strGroup hasPrefix: @"#"]; 

    if (result) 
    { 
     result = [strGroup hasSuffix: @"#"]; 

     if (result) 
     { 

      NSMutableString* string = [NSMutableString stringWithString: strGroup]; 
      str = [strGroup substringWithRange: NSMakeRange (1, [string length]-2)]; 

      strToHoldAllContact = [NSString stringWithFormat:@"%@",str]; 
     } 
    } 
    NSLog(@"strToHoldAllContact=%@",strToHoldAllContact); 
} 

我正確剛開的strToHoldAllContact值。但是,當我嘗試從另一個方法,我得到的錯誤訪問strToHoldAllContact:你在哪裏都被初始化或設置字符串

[CFString respondsToSelector:]: message sent to deallocated instance 0x856f2a0 
+0

保留它。或者它會被自動釋放;像「strToHoldAllContact = [[NSString stringWithFormat:@」%@「,str] retain];」不要忘了釋放它時dealloc – adali 2012-04-28 06:48:58

+0

對不起,我不使用ARC,或者他可以使用屬性來解決問題, – adali 2012-04-28 06:57:05

回答

0

做到這一點[strToHoldAllContact retain];,不要忘記將其釋放,一旦你用它做

0

只需更換

strToHoldAllContact = [NSString stringWithFormat:@"%@",str]; 

strToHoldAllContact = [[NSString alloc] initWithFormat:@"%@",str]; 

然後在你不再需要它的時候釋放它。

1

使用

strToHoldAllContact = [NSString stringWithFormat:@"%@",str]; 
[[strToHoldAllContact retain] autorelease]; 

,而忘記了釋放。

0

與ARC,在.H聲明strToHoldAllContact爲:在.M

@property(strong) NSString *strToHoldAllContact; 

,使用它(@synthesize之後)爲self.strToHoldAllContact = [NSString stringWithFormat:@"%@",str]; 這樣你不會有問題。

沒有ARC,在.H聲明strToHoldAllContact爲:

@property(retain) NSString *strToHoldAllContact; 

,並用它相同的方式與ARC in.m文件。