I am开发者_JS百科 playing with AppKit and NSDocument and I don't know why this is not working?:
I just wrote this and image is not nil but never loads any image, its size is always zero. Is this the correct method I have to implement to read files into my document? I need the path, not the data (NSData) because I plan to use other library to read other files.
Now I am trying to read PNGs, JPGs , none worked. ;(
- (BOOL) readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError{
NSImage *image = nil;
image = [[NSImage alloc] initWithContentsOfURL:url];
[imageView setImage:image];
[image release];
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return YES;
}
Thanks in advance.
Do it this way:
NSImage *image = [[NSImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
If imageView is being loaded from a NIB file, it will not have been set when readFromURL:ofType:error: is called. Instead, you should load the image and store it in an instance variable, then add it to the imageView in the windowControllerDidLoadNib: method. Also, you are returning an error every time, while you should only return an error if something goes wrong.
- (void)windowControllerDidLoadNib:(NSWindowController *)windowController {
[imageView setImage:image];
[image release];
image = nil;
}
- (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError {
image = [[NSImage alloc] initWithContentsOfURL:url];
if(!image) {
if(outError) *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
return NO;
}
return YES;
}
Just make sure you add a NSImage *image; instance variable to your header file.
精彩评论