problem in nsstring release
i have a problem when i release data22 then exception occur and when i comment this line their is no error. what is the reason.
NSString *data22=[[NSString alloc] init];
data22=@"";
for (int i=0;i<[emailData count] ; i++) {
NSString *csv =[NSString stringWithFormat:@"\"%@\",\"%@\"",[[emailData objectAtIndex:i] keyword],[[emailData objectAtIndex:i] note]];
data22=[NSString stringWithFormat:@"%@%@",data22,csv];
if(i<[emailData count]-1)
data22=[NSString stringWithFormat:@"%@\n",data22,csv];
}
[@"" writeToFile:toPath atomically:YES];
NSFileHandle *writeHandle=[NSFileHandle fileHandleForWritingAtPath:toPath] ;
[writeHandle writeData:[data22 dataUsingEncoding:NSUTF8StringEncoding]];
when i write this line of code then after completing this method an exception occurs
[data22 release];
remaining method
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"AKW Keywords"];
picker.navigationBar.barStyle = UIBarStyleBlack; // Translucent UIBarStyleBlack;
// Set up recipients
NSData *myData2 =[NSData dataWithContentsOfFile:toPath];
[picker addAttachmentData:myData2 mimeType:@"text/csv" fileName:@"awk.csv"];
// Fill out the email body text
NSString *emailBody = @"";
[picker se开发者_如何转开发tMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
NSLog(@"after release");
}
A string returned with stringWithFormat is not owned by your code unless you explicitly retain it. You should not release objects you don't own.
This is the difference between using [NSString stringWithFormat: ...]
and [[NSString alloc] initWithFormat: ...]
; stringWithFormat returns an object that's been scheduled for releasing. Unless you retain it, that release will dispose of it. initWithFormat returns an object with an effective retain count of 1; it's up to you to dispose of it.
Assuming this is all in one method, you can fix this by not calling release on the string. However, this assumes a bunch of stuff that may or may not be true of your code. You REALLY need to read Apple's documentation on memory management: Memory Management Programming Guide. It's a few pages, and covers both the rules and some simple examples of their use.
Calling stringWithFormat is enough to get a valid string object that you can use, but you must not release it afterwards because you haven't created it (using alloc). If you want to pass the string to some other function, retain it and release it in that other function once you're done with it.
Also, you are causing a memory leak by first calling alloc on data22, then calling stringWithFormat and assigning the object to data22 again, without first releasing the old object.
EDIT: Just delete this
NSString *data22=[[NSString alloc] init];
data22=@"";
and replace it with
NSString* data22;
and it will work if you will only be using stringWithFormat function. You never have to release data22 this way.
精彩评论