Objective-c : cannot init a class object - objective-c

I am getting an issue cannot init a class object even after adding lines to the constructor such as
self = [super init];
or
self = [[super init] alloc];
And I am not sure what to do.
This is the specific error:
file:///%3Cunknown%3E: test failure: -[LinkedListTest testAdd] failed: *** +[NList<0x8e14> init]: cannot init a class object.
.m
#interface NList()
#property (weak, nonatomic, readwrite) NSObject *head;
#property (nonatomic,readwrite) NSInteger *size;
#end
#implementation NList
#synthesize size = _size;
- (id) init:(NSInteger *)size {
//is this even necessary? I don't want object methods.. or do I ?
if (self){
_head = nil;
_size = size;
}
return self;
}
.h
#interface NList : NSObject
#property (nonatomic,readonly) NSInteger *size;
#property (weak, readonly, nonatomic) NSObject *head;
- (void)add:(NSObject *)node;
#end
test class
- (void)testAdd
{
NList *testList = [[NList init] alloc];
// Card *testCardOne = [[Card init] alloc];
// [testList add:(testCardOne)];
XCTAssertNotNil(testList.head);
}
I have tried adding the line
self = [[super init] alloc];
to the constructor to no avail.
No visible interfacce for nlist declares
or self = [super init]
complains cannot init a class object!
EDIT
I realized that it is not asking me for the size! the constructor requires a size parameter...how do I do this! Ahh [looks up docs]

A few things.
You need a default constructor
- (id)init {
self = [super init];
if (self) {
self.head = nil;
}
return self;
}
Now that you have a default constructor (that calls the superclasses constructor), you need a more specific one for your purposes.
- (id)initWithSize:(int)size {
self = [self init]; // sets head, calls super constructor.
if (self) {
self.size = size;
}
return self;
}
Edit: Note, the last one had to be in your .h file so it is visible.
And also, when instantiating this class, call
NList *list = [[NList alloc] initWithSize:mySize];

You're a little backwards.
How about:
NList *testList = [[NList alloc] init:SIZE];
where size is the SIZE init you want to use.
Alloc comes before init when you're instantiating Objective-C objects.

Related

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"];
}
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).

Why can't I populate my controller with items?

I'm using an ItemController to provide a list of items to use in a tableview. I can't seem to populate the controller though, and I'm not sure why.
Here's the code for the controller class:
.h
#import <Foundation/Foundation.h>
#class Item;
#interface ItemController : NSObject
#property (nonatomic, copy) NSMutableArray *items;
- (NSUInteger)countOfList;
- (Item*)objectInListAtIndex:(NSUInteger)theIndex;
- (void)addItem:(Item *)item;
#end
.m
#import "ItemController.h"
#import "Item.h"
#interface ItemController ()
#end
#implementation ItemController
- (NSUInteger)countOfList {
return [self.items count];
}
- (Item *)objectInListAtIndex:(NSUInteger)theIndex {
return [self.items objectAtIndex:theIndex];
}
- (void)addItem:(Item *)item {
[self.items addObject:item];
}
#end
Item.m
#implementation Item
-(id)initWithName:(NSString *)name{
self = [super init];
if (self) {
_name = name;
return self;
}
return nil;
}
#end
I'm using the following code to populate the list:
ItemController* controller = [[ItemController alloc] init];
for (NSString* key in raw_data) {
NSLog(key); // This outputs the keys fine
[controller addItem:[[Item alloc] initWithName:key]];
}
NSLog([NSString stringWithFormat:#"%d",[controller countOfList]]); // Always 0
You need to initialize the array in the init methond.
- (id)init {
self = [super init];
if (self) {
self.items = [[NSMutableArray alloc] init];
}
return self;
}
You need to initialize your variable items. In your init method, call self.items = [NSMutableArray new]; and also change your array property from copy to retain.
I also believe your class ItemController should be of kind UIViewController and not NSObject.
#interface ItemController : UIViewController
You don't initialise the _items instance variable anywhere, so it's always nil. The result of any integer-returning method called on nil will be 0, so you see that the count is 0.

Designated initializer and passing arguments

I have this hierarchy:
CreateAnObjectClass : NSObject
MySecondClass : MyBaseClass
MyBaseClass : NSObject
in CreateAnObjectClass I want to create an instance of MySecondClass method and i want to pass a #property (strong,nonatomic) NSDictionary* myTemplate to myBaseClass.
For example:
CreateAnObjectClass *testObj = [[MySecondClass alloc] initWithTemplate:myTemplate];
And I know that calls both initializers from MyBaseClass and MySecondClass.
(id)initWithTemplate:(NSDictionary*)myTemplate
{
self = [super init]
return self;
}
My question is how I should designe initializers to myTamplate can be a property at MyBaseClass?
Like this:
- (id)initWithTemplate:(NSDictionary*)aTemplate
{
self = [super init]
if (self){
self.myTemplate=aTemplate;
}
return self;
}
Edit 1:
Remember the following, calling this:
self = [super init];
On the MySecondClass will call the init method on the MyBaseClass

Mutable array contents are lost between methods

I have this code in my .m file, which is a Cocos 2D CCLayer class. I initialize an array in the init method and then I try to use contents of this array in the nextFrame method. But when the nextFrame method gets called, the contents of the array seem empty. When I try to get the first item, I receive an error message saying:
Program received signal "EXC_BAD_ACCESS"
How can I successfully access the contents of this array in my nextFrame method?
NSMutableArray *cars;
-(id) init {
cars = [NSMutableArray array];
Car *car;
car = [[Car alloc] init];
[cars addObject:car];
self.isTouchEnabled = YES;
}
- (void) nextFrame:(ccTime)dt {
Car *car = [cars objectAtIndex:i]; // Program received signal "EXC_BAD_ACCESS"
}
Car.h
#import <Foundation/Foundation.h>
#import "cocos2d.h";
#interface Car : NSObject {
NSInteger type;
CCSprite *sprite;
}
#property (readwrite, assign) NSInteger type;
#property (retain) CCSprite *sprite;
#end
Car.m
#import "Car.h"
#implementation Car
#synthesize type;
#synthesize sprite;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void) dealloc {
[sprite release];
[super dealloc];
}
#end
You're assigning the result of [NSMutableArray array] to an instance variable. That is an autoreleased object, which essentially means it doesn't have any owners and thus will feel free to go away after the current runloop iteration*. You need to retain it if you want it to stick around (or just use [[NSMutableArray alloc] init], which returns an object you own).
* Basically. You should see the Cocoa memory mangement guide for more details. It's pretty short but full of essential information.

Memory leak with objective-c on alloc

When I use Instruments to find memory leaks, a leak is detected on
Horaires *jour;
jour= [[Horaires alloc] init]; // memory leak reported here by Instruments
self.lundi = jour;
[jour release];
and I don't know why there is a leak at this point.
Does anyone can help me? Here's the code.
// HorairesCollection.h
#import <Foundation/Foundation.h>
#import "Horaires.h"
#interface HorairesCollection : NSObject < NSCopying > {
Horaires *lundi;
}
#property (nonatomic, retain) Horaires *lundi;
-init;
-(void)dealloc;
#end
// HorairesCollection.m
#import "HorairesCollection.h"
#implementation HorairesCollection
#synthesize lundi;
-(id)copyWithZone:(NSZone *)zone{
HorairesCollection *another = [[HorairesCollection alloc] init];
another.lundi = [lundi copyWithZone: zone];
[another autorelease];
return another;
}
-init{
self = [super init];
Horaires *jour;
jour= [[Horaires alloc] init]; // memory leak reported here by Instruments
self.lundi = jour;
[jour release];
return self;
}
- (void)dealloc {
[lundi release];
[super dealloc];
}
#end
// Horaires.h
#import <Foundation/Foundation.h>
#interface Horaires : NSObject <NSCopying>{
BOOL ferme;
BOOL h24;
NSString *h1;
}
#property (nonatomic, assign) BOOL ferme;
#property (nonatomic, assign) BOOL h24;
#property (nonatomic, retain) NSString *h1;
-init;
-(id)copyWithZone:(NSZone *)zone;
-(void)dealloc;
#end
// Horaires.m
#import "Horaires.h"
#implementation Horaires
-(BOOL) ferme {
return ferme;
}
-(void)setFerme:(BOOL)bFerme{
ferme = bFerme;
if (ferme) {
self.h1 = #"";
self.h24 = NO;
}
}
-(BOOL) h24 {
return h24;
}
-(void)setH24:(BOOL)bH24{
h24 = bH24;
if (h24) {
self.h1 = #"";
self.ferme = NO;
}
}
-(NSString *) h1 {
return h1;
}
-(void)setH1:(NSString *)horaire{
[horaire retain];
[h1 release];
h1 = horaire;
if (![h1 isEqualToString:#""]) {
self.h24 = NO;
self.ferme = NO;
}
}
-(id)copyWithZone:(NSZone *)zone{
Horaires *another = [[Horaires alloc] init];
another.ferme = self.ferme;
another.h24 = self.h24;
another.h1 = self.h1;
[another autorelease];
return another;
}
-init{
self = [super init];
return self;
}
-(void)dealloc {
[h1 release];
[super dealloc];
}
#end
You've set your property to retain and you alloc and release the variable, so from what I can see the code is okay and Instruments has given you a false warning.
I think your copyWithZone: might have a leak, though. [lundi copyWithZone:] will retain a copy of lundi but you never release it. So you need an extra release, something like this:
-(id)copyWithZone:(NSZone *)zone{
DefibHoraires *another = [[DefibHoraires alloc] init];
Horaires* makeCopy = [lundi copyWithZone: zone];
another.lundi = makeCopy;
[makeCopy release];
return another;
}
This is because copy and alloc both return retained object instances and you need to manually release them when you're finished with them. You did that correctly for your alloc'd objects but not the copy.
That init method looks ok, although it should be implemented (and typed) as
-(id)init
{
if (self = [super init])
{
...
}
return self;
}
or a similar pattern.
Your copyWithZone implementations are wrong, they need to return a retained object, so do not autorelease the returned value. But you need to release your copy of lundi, because you are using the retaining setter.
-(id)copyWithZone:(NSZone *)zone{
DefibHoraires *another = [[DefibHoraires alloc] init];
Horaires *lundiCopy = [lundi copyWithZone:zone];
another.lundi = lundiCopy;
[lundiCopy release];
return another;
}
I don't know why you return an instance of DefibHoraires here, shouldn't it be a HorairesCollection?
Maybe the wrong copyWithZone: method is responsible for the reported leak (it's a leak anyway).
One further note: It's a good defensive rule to use (copy) for NSString properties instead of (retain) to remove side effects when passing NSMutableString instead.
I don't have an answer but I do have some general comments:
In copyWithZone: you should use allocWithZone: (passing the same zone as a parameter) to allocate the object you are going to return.
copyWithZone: should return a retained object. Don't autorelease it.
You are not supposed to use properties in init. Your init should look something like:
-init
{
self = [super init];
if (self != nil)
{
lundi = [[Horaires alloc] init]; // assign the ivar directly
}
return self;
}
In your copyWithZone: for HorairesCollection you have a leak. It should look like:
-(id)copyWithZone:(NSZone *)zone{
DefibHoraires *another = [[DefibHoraires allocWithZone: zone] init];
another.lundi = [[lundi copyWithZone: zone] autorelease];
return another;
}