質問

I have a class WebServices that inherits from NSObject. I am using xcode4.2 and ARC turned on. When I created the class, there was no other method in the NSObject lie viewDidLoad or init.

The issues is that when I try to call self.something or [self someMethod] Xcode flags my code red and complains with:

implicit conversion of Objective-C pointer type 'Class' to C pointer type 'struct obj_class*' requires a bridge cast

Please help. Why isn't cocoa like java where you call "this" and get the object you are in?

// WebService.h file
@interface WebService : NSObject

@property (weak, nonatomic) NSString * myString;
+(void) setAndPrintMyString:(NSString*) someString;

@end



//WebService.m file


#import "WebService.h"
@implementation WebService

@synthesize myString=_myString;

+(void) printMyString:(NSString*) someString{
 [self setMyString:someString];      //XCode does not allow
 NSLog(@"myString is set to %@",self.myString); //XCode dose not allow
}

@end
役に立ちましたか?

解決

Declaring a method with + means that it is a class method. Within a class method self refers to the class itself, which in your case would be [WebService class]. If you declared and instance method (using -) then inside the method self would refer to the instance, which is what you want.

To set an instance variable - you need an instance

WebService *webService = [[WebService alloc] init];
webService.myString = @"some string";

Now to make your method work you need to declare it with a - instead of + which makes it an instance method

- (void)printMyString:(NSString *)someString
{
  [self setMyString:someString];
  NSLog(@"myString is set to %@",self.myString);
}

Now

[webService printMyString:@"boom"];

results in the instance variable myString being set to boom and the console logging out `myString is set to boom".

他のヒント

viewDidLoad method doesn't fit with NSObject subclass. It's a method for UI which will be there in UIViewController subclasses.

Now, Coming to point about self.something OR [self someMethod], That works perfectly well with NSObject subclasses. You need to show us the code, in which you are facing problem.

Just for your reference (I think you should start developing for iOS after going through this):

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top