Problems with NSString inside viewWillDisappear

2019-08-30 04:44发布

问题:

I am battling with this piece of code for days now, I really would appreciate your insight. So here it is...

fileName which is declared in my .h file as

    NSString *fileName;

and later as

    @property (nonatomic, copy) NSString *fileName;

is not accessible inside viewWillDisappear. It just shows up as nil object, or some weird value when I debug. When I debug, my console show this msg:

Printing description of fileName: FileNumber1

When I reach to viewWillDisappear my console shows this:

Printing description of fileName:

Yeah, just nothing for fileName.. the value simply disappears.. I just don't know why!!!

MORE DETAILS:

Inside my init method I do the following and it works fine.

    fileName = [[NSString alloc] initWithString:(NSString *)CFURLGetString(pdfURL)]; 
    fileName = [[fileName lastPathComponent] stringByDeletingPathExtension];
    fileName = [fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Throughout the program I can access fileName just fine, but inside viewWillDisappear I am trying to save to my standardUserDefaults by attempting the following:

    NSUserDefaults *ud = [[NSUserDefaults standardUserDefaults] autorelease];
    NSArray *tmp = [NSArray arrayWithArray:someMutableArray];
    [ud setObject:tmp forKey:fileName];    // THE PROBLEM IS HERE WITH fileName AS AKEY
    [ud synchronize];
    [tmp release];

At this point someMutableArray is accessible, but fileName is not. Any insight, thoughts, ideas, will be appreciated.

回答1:

in your init method change it to read self.fileName =

You need to use your property methods so that a copy of the string will be made, currently because you are using the variable rather than the property you are assigning an autoreleased string. By using self.fileName the string will be copied and will not be autoreleased.