NSMtringString到NSstring导致“消息发送到解除分配的实例”

时间:2010-12-18 21:35:01

标签: iphone nsstring nsmutablestring

我在NSMutableString,localPName中有数据。我想像这样保存用户的数据:

[[NSUserDefaults standardUserDefaults] setObject:aString forKey:@"thePNameKeyValue"];

编译器正在努力教我“发送到解除分配的实例的消息。”除了合成和单次使用(打印有效数据)之外,我没有看到localPName被触及的位置,更不用说“解除分配”了。 ,“发布,等等。

NSMutableString *localPName;
NSString        *whateverNSString;
@property(nonatomic,retain) NSMutableString *localPName;
@property(nonatomic,retain) NSString *whateverNSString;


@synthesize localPName;
@synthesize whateverNSString;
localPName = [[NSMutableString alloc] initWithCapacity:40];
//  [localPName appendString:@""];  ← seems to make no difference

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSMutableString *teststring=[NSMutableString stringWithString:textField.text];
    localPName = teststring;
    NSLog(@"at textFieldDidEnd, localPName='%@'",localPName);   // ← prints correct data
}

从现在开始,我几乎要去吃午饭。

回应“你有什么尝试?”我已经包含了许多我从网上提出的建议。 How to initialize NSString to NSMutableString? Objective-C "message sent to deallocated instance 0x5633b0" 上面的结果是: (gdb)信息符号0x2f699fe0 没有符号匹配0x2f699fe0。

//  1
//NSString *str1 = @""; 
//  str1 = [str1 stringByAppendingString:localPName];
//  2
//  NSString *str1 = [[NSString alloc] initWithString:localPName];
//  3
//  whateverNSString = [[NSString alloc] initWithString:localPName];
//  4
//  whateverNSString =localPName;   //  message sent to deallocated instance, nonatomic,retain
//  5
//  self.whateverNSString =localPName;  //  message sent to deallocated instance, nonatomic, retain
//  6
//  whateverNSString =localPName;   //  message sent to deallocated instance, nonatomic, retain
//  7
//  glbl_asNeededInt = [whateverNSString length];   //  message sent to deallocated instance, nonatomic, copy
//  NSLog(@"saveButton 3 length=%d",glbl_asNeededInt);
//  8
//  whateverNSString = localPName;  //  crash. no crash log, no console. no nuthin' 
//  9
//  https://stackoverflow.com/questions/1354490/how-to-take-an-nsstring-out-of-an-nsmutablestring
//  whateverNSString = [localPName copy];
//  10
//  whateverNSString = (NSString*) localPName;
//  11
//  NSString* aString = [NSString stringWithFormat: @"%@", localPName]; // message sent ...
//  12
// NSString* aString = [NSString stringWithString:localPName];  // message sent ...

假期即将到来。我要感谢那些可能有助于我早早收到礼物的人。

1 个答案:

答案 0 :(得分:2)

testString指向您直接分配给实例变量的autoreleased实例。你应该使用setter:

self.localPName = teststring;

使用它来获取字符串的所有权(setter通过保留实例来获取所有权),并且您也不会泄漏之前分配给它的实例(它将由setter正确释放)。