Hey guys, new to Objective-C. I'm pretty confident what I'm not doing right is easy and I just don't understand things 100%. If anyone could help me out that'd be great.
Does anyone see anything wrong with the following method? The first time through it works, the second time through it always goes into the if( content == nil ) code, and the third time it will crash.
If I remove all the release methods it works perfectly and doesn't go into the if( content == nil ) code.
Okay, it works if I comment [stringURL release] and leave the other release methods in there. Can anyone explain what I'm doing wrong with releasing stringURL?
Can you explain how changing the pointer stringURL would cause an error? I don't understand why it would because I'm allocating/initializing it at the beginning of the method.
I assume that other parts of the app are calling [stringURL appendFormat:] or [stringURL appendString:] ; that's fine. You're just calling some methods on the existing object.
However if you're doing something like stringURL = [NSMutableString string] elsewhere in your app, then your stringURL is now pointing at a new string that gets autoreleased and will probably cause a crash if you release it again.
If the crash is really caused by [stringURL release] then you should examine every line that says stringURL = blah.
EDIT: Oh, or if someone else is asking for someVar = thisObject.stringURL and keeping the value around and not retaining it. For example, this would cause a crash with your original code:
Code:
[thisObject getIP: someURL];
NSString *someVar = thisObject.stringURL;
[thisObject getIP: someURL];
//anything I do with someVar now will cause a crash; you released the string and I didn't retain it.
NSlog(@"%@", someVar);
Ah! It's the encoding. You're expected to pass the address of an encoding variable, and the call fills in that variable with the encoding that was used. It looks like you're creating a pointer and passing the value of that pointer - which is probably nil.
Try this instead:
Code:
NSStringEncoding enc; // no *; this is not a pointer
// pass in &enc; the address of your enc variable
content = [[NSMutableString alloc] initWithContentsOfURL: URL
usedEncoding: &enc
error: NULL];
The difference is that this code creates *space* for an encoding, and passes the address of that space for the method to write into. You code creates a *pointer* to an encoding, and passes in the value of that pointer (nil by default).
This is an example of pass-by-reference, a technique to return multiple values from a C function (or an objc method).