Search code examples
cocoa-touchios6xcode4.2implicit-conversionnsobject

NSObject call to self gives XCode error


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

Solution

  • 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".