devheedoo devheedoo - 1 month ago 6
Objective-C Question

No known class method for selector 'initWith...'

I found similar questions, but I couldn't solve my error. My error is:


No known class method for selector 'initWithUrl:sub:cont:cat:dat'


I've tried


  • @Synthesize
    ,

  • self.variableName
    instead of
    _variableName
    ,

  • adding
    [[MyClass init] alloc]
    ,

  • changing
    -
    to
    +



How can I fix it?

MyClass.h:

#import <Foundation/Foundation.h>

@interface MyClass : NSObject

-(id)init;
-(id)initWithURL:(NSURL *)url_ sub:(NSString *)subject_ cont:(NSString *)content_ cat:(NSString *)category_ dat:(NSString *)date_;

@property NSURL *bannerImageURL;
@property NSString *subject;
@property NSString *content;
@property NSString *category;
@property NSString *date;

@end


MyClass.m:

#import "MyClass.h"

@implementation MyClass

// 객체 초기화
-(id)init {
self = [super init];
if (self) {
_bannerImageURL = [NSURL URLWithString:@"url0"];
_subject = @"sub0";
_content = @"cont0";
_category = @"cat0";
_date = @"dat0";
}
return self;
}

-(id)initWithURL:(NSURL *)url_ sub:(NSString *)subject_ cont:(NSString *)content_ cat:(NSString *)category_ dat:(NSString *)date_ {
self = [super init];
if (self) {
_bannerImageURL = url_;
_subject = subject_;
_content = content_;
_category = category_;
_date = date_;
}
return self;
}

@end


myViewController.m:

#import "myViewController.h"
#import "MyClass.h"

@implementation SimpleTableViewController

MyClass *news1;

- (void)viewDidLoad {
[super viewDidLoad];
NSURL *aUrl = [NSURL URLWithString:@"aUrl"];

// Error occurs here.
news1 = [MyClass initWithURL:aUrl sub:@"aSub" cont:@"aCont" cat:@"aCat" dat:@"aDat"];
}

Answer

I think you mean:

news1 = [[MyClass alloc] initWithURL:aUrl sub:@"aSub" cont:@"aCont" cat:@"aCat" dat:@"aDat"];

This is a standard pattern in Objective-C: call [SomeClass alloc] to create a new instance, then immediately call some initializer method on it. Initializers are instance methods which must be called on an instance of a class, whereas alloc is a class method that is called on the class itself (and which returns a newly allocated instance of that class).