Page 1 of 1

Objective C code problem

Posted: Sat Nov 17, 2007 11:01 am
by bcnipod
ok here is my problem. i am building a application that will open .txt files, you can then edit them and save them. the save function works, the editing works, but i cannot get it to open them. I am writing this in Objective C and whenever i try to open a .txt file it crashes the application. I am building this in Xcode. Here is the code i am using:

Code: Select all

- (IBAction)openTextFile:(id)sender

{

	NSOpenPanel *theOpenPanel = [NSOpenPanel openPanel];

	if ([theOpenPanel runModal] == NSOKButton)

	{

		NSString *theFileName = [theOpenPanel filename];

		NSString *theFileContents = [NSString stringWithContentsOfFile:theFileName];

		[theTextView setString:theFileContents];

		[theFileName release];

		[theFileContents release];

	}

}


Re: Objective C code problem

Posted: Mon Nov 19, 2007 11:43 am
by Prey
Heh, Mac coding. Well I've never used the language, or owed a MAC, but perhaps try not releasing the 'theFileContents'. But if SetString does actually copy the string, then.. maybe it is because you are not releasing the 'theOpenPanel'?

[/guess]

Posted: Mon Nov 19, 2007 2:31 pm
by bcnipod
ok i just tried that and it did not work.

Posted: Wed Nov 21, 2007 2:36 am
by dfmjw
hey i have never used Objective C either. but would i would suggest is adding 101 printf(char* message); statements if needed just to find out where it fails. The error you got when your program crashes would be helpful. not sure if Xcode has a debugger but a few breakpoints would help. i also found something on reading txt files in objective C it used a different reading function than you did. http://maccoder.blogspot.com/2007/02/re ... using.html
initWithContentsOfFile:(NSString *)
worst comes to worst use stdio functions and read out the contents out as a char* and then convert to a NSString object. assuming there is some way of doing that.

and like prey said releasing the NSString theFileContents is not a good idea if you are not certain what it does with the NSString pointer when you call the [theTextView setString:theFileContents]; like if it copys the contents of NSString* or just copys the pointer.