Why is NSString returning null? - objective-c

#import <Foundation/Foundation.h>
//-----Interface-----
#interface Person: NSObject{
int age;
int weight;
NSString *name;
}
-(void) print;
-(void) setAge: (int) a;
-(void) setWeight: (int) w;
-(void) setName: (NSString*) n;
#end
//-----Implementation-----
#implementation Person
-(void) print{
NSLog(#"%# is %i years old and my weight is %i pounds", name, age, weight);
}
-(void) setAge: (int) a{
age=a;
}
-(void) setWeight: (int) w{
weight=w;
}
-(void) setName: (NSString*) n{
name=n;
}
#end
//-----Main Program-----
int main(int argc, const char * argv[]) {
#autoreleasepool {
Person *james = [[Person alloc]init];
Person *bob = [[Person alloc]init];
[james setAge: 55];
[james setWeight: 400];
[james print];
[bob setAge: 80];
[bob setWeight: 150];
[bob print];
}
return 0;
}
It should return "james is 55 years old and my weight is 400 pounds" and "bob is 80 years old and my weight is 150 pounds"
But instead of "bob" and "james" I am getting "(null)"
Any ideas of why this could be happening?

You're not actually calling setName anywhere in your code ;) Try:
// ... other code happens here, then:
#autoreleasepool {
Person *james = [[Person alloc]init];
Person *bob = [[Person alloc]init];
[james setAge: 55];
[james setWeight: 400];
[james setName: #"james"]; // you need this
[james print];
[bob setAge: 80];
[bob setWeight: 150];
[bob setName: #"bob"]; // and this
[bob print];
}
In the end, bear in mind that just because you created a class instance with a particular name (in this case james and bob), doesn't explicitly set a property such as name.
You might try something a little clever like adding an initialization method to inside your class:
In your header/interface:
- (id) initWithName:(NSString*)name;
And in your implementation:
- (id) initWithName:(NSString*)name
{
self = [super init];
if (self != nil)
{
[self setName:name];
}
return self;
}
Then you can call:
Person *james = [[Person alloc]initWithName:#"james"];

it seems you never call something like [james setName:#"james"] so name property is never initialised

Related

With ARC , why the dealloc not called

I have enable the ARC. but this code makes me wonder
#interface Dog : NSObject
#end
#implementation Dog
- (void)dealloc
{
printf("Dog is dealloc\n"); //the function not called
}
#end
#interface Person : NSObject
#property (nonatomic, strong) Dog *dog;
#end
#implementation Person
- (void)dealloc
{
printf("Person is dealloc\n");
_dog = nil;
}
-(Dog *)dog
{
return _dog;
}
#end
int main()
{
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc]init];
Dog* d = p.dog;
d=nil;
p=nil;
printf("end\n");
return 0;
}
the result is
Person is dealloc
end
Program ended with exit code: 0
why the dog's dealloc method not called.
and then I commented out this Method, the dog's dealloc method called.
//-(Dog *)dog
//{
// return _dog;
//}
thank you very much.
You can see the memory graph to find out what exactly points to the Dog and preserve it from automatically deallocation:
Unlike Swift, In Objective-C, you need to put the main body inside an #autoreleasepool to make it ARC compatible:
int main(int argc, const char * argv[]) {
#autoreleasepool {
// insert code here...
NSLog(#"Hello, World!");
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc]init];
Dog* d = p.dog;
d = nil;
p = nil;
printf("Ended...\n");
}
return 0;
}
Then you will see this in the output:
Person is dealloc
Ended...
Dog is dealloc

Why weak property of associated object is not nilled out if I call its getter?

Though it's kind of stupid in 2020 that I'm still asking question about ObjC, please be patient and considerate...
I'm reading the source code of BloksKit and ran into a weird situation.
#import <objc/runtime.h>
#interface _WeakAssociatedObjectWrapper : NSObject
#property (nonatomic, weak) id object;
#end
#implementation _WeakAssociatedObjectWrapper
#end
#interface NSObject (AddWeak)
#end
#implementation NSObject (AddWeak)
- (void)setWeakProp:(id)weakProp {
_WeakAssociatedObjectWrapper *wrapper = objc_getAssociatedObject(self, #selector(weakProp));
if (!wrapper) {
wrapper = [[_WeakAssociatedObjectWrapper alloc] init];
objc_setAssociatedObject(self, #selector(weakProp), wrapper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
wrapper.object = weakProp;
}
- (id)weakProp {
id value = objc_getAssociatedObject(self, _cmd);
if ([value isKindOfClass:_WeakAssociatedObjectWrapper.class]) {
return [(_WeakAssociatedObjectWrapper *)value object];
}
return value;
}
#end
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSObject *obj = [[NSObject alloc] init];
{
NSObject *prop = [[NSObject alloc] init];
[obj setWeakProp:prop];
[obj weakProp]; // *Weird!!
}
NSLog(#"Now obj.weakProp = %#", [obj weakProp]);
}
return 0;
}
This code is adding a weak associated object for category.(BlocksKit does so)
Note the *Weird!! line. If this line is commented out, then it prints (null), which is reasonable since prop is deallocated outside the {} scope. On the other side, if not commented out, it prints <NSObject: 0xxxxx>, which indicates that prop is somehow retained by someone(Or any other reason?).
What is happening here??! (BlocksKit behaves the same!)
Environment: XCode 10.3
This is a feature. For the case (and any similar)
[obj weakProp];
by properties/accessors naming convention ARC returns autoreleased instance, so in your case #autoreleasepool holds it and testing as below can show this.
int main(int argc, const char * argv[]) {
NSObject *obj = [[NSObject alloc] init];
#autoreleasepool {
{
NSObject *prop = [[NSObject alloc] init];
[obj setWeakProp:prop];
[obj weakProp]; // *Weird!!
}
NSLog(#"Now obj.weakProp = %#", [obj weakProp]);
}
NSLog(#"After autoreleased >> obj.weakProp = %#", [obj weakProp]);
return 0;
}

How to stop addObject from overwriting all previous objects in a NSMutableArray

addObject is overwriting all the previous cells. So if the array is size 4, adding the objects increases the size, but it also overwrites all other cells with the same thing.
groups = [[NSMutableArray alloc]init];
[groups addObject:[[Group alloc] init]];
[[groups objectAtIndex:0] setGroupName:#"cs480"];
[[groups objectAtIndex:0] setPassword:#"apple1"];
[groups addObject:[[Group alloc] init]];
[[groups objectAtIndex:1] setGroupName:#"cs481"];
[[groups objectAtIndex:1] setPassword:#"apple2"];
+(void) print{
NSLog(#"size: %lu",(unsigned long)[groups count]);
for(int i = 0; i < [groups count]; i++){
Group *group = [groups objectAtIndex:i];
NSLog(#"%#\t%#\n",[group getGroupName], [group getPassword]);
}
}
The group class is
#import <Foundation/Foundation.h>
#import "Group.h"
#import "Person.h"
#import "Pie.h"
#implementation Group
NSString* groupName;
NSString* password;
NSMutableArray *groupMembers;
NSMutableArray *skillsOfMembers;
-(id) init{
self = [super init];
if(self){
NSLog(#"inside group constructor");
groupMembers = [[NSMutableArray alloc] init];
skillsOfMembers = [[NSMutableArray alloc] init];
groupName = [[NSString alloc]init];
password = [[NSString alloc]init];
}
return self;
}
-(NSInteger) authenticate:(NSString *)checkGroupName :(NSString *)checkPassword{
if([checkGroupName isEqualToString:groupName]&&[checkPassword isEqualToString:password]){
return 1;
}
return 0;
}
-(void) setGroup:(NSMutableArray*)newGroupMembers{
groupMembers = newGroupMembers;
}
-(NSMutableArray*) getGroup{
return groupMembers;
}
-(Person*) getPerson:(int) index{
return [groupMembers objectAtIndex:index];
}
-(void) setPerson:(int) index :(Person*) newPerson{
Person* person = [groupMembers objectAtIndex:index];
person = newPerson;
}
-(NSMutableArray*) getSkillsOfPerson:(int)index{
return [skillsOfMembers objectAtIndex:index];
}
-(void) setSkillsOfPerson:(Pie*) newSkills :(int)index{
Pie *skillsOfMember = [skillsOfMembers objectAtIndex:index];
skillsOfMember = newSkills;
}
-(void) setGroupName:(NSString*) newName{
groupName = [newName copy];
}
-(NSString*) getGroupName{
return groupName;
}
-(void) setPassword:(NSString*) newPassword{
password = [newPassword copy];
}
-(NSString*) getPassword{
return password;
}
#end
The output is
2014-11-10 13:23:19.013 Balanced Team Pie[1964:66289] size: 2
2014-11-10 13:23:19.013 Balanced Team Pie[1964:66289] cs481 apple2
2014-11-10 13:23:19.014 Balanced Team Pie[1964:66289] cs481 apple2
What is the issue?
These:
#implementation Group
NSString* groupName;
NSString* password;
NSMutableArray *groupMembers;
NSMutableArray *skillsOfMembers;
are not instance variables. They are just global variables. They are declared at file scope. The fact that they come between #implementation and its corresponding #end means nothing to the compiler.
Effectively, there's one set of variables for the whole program, rather than one set of variables for each instance of the Group class.
You probably meant:
#implementation Group
{
NSString* groupName;
NSString* password;
NSMutableArray *groupMembers;
NSMutableArray *skillsOfMembers;
}
The curly braces are required to make the variables instance variables.

Objective-C - Mac NSLog not working

I am new to Obejctive-C as well as Mac. I have been trying to learn online and have written this simple piece of code , but the NSLog doesn't work for me.
#import <Foundation/Foundation.h>
#interface Person : NSObject{
int age ;
int weight;
}
-(void) print;
-(void) setAge:(int) a;
-(void) setWeight:(int) w;
#end
//---implementation---
#implementation Person
-(void) print{
NSLog(#"I am %i years and my weight is %i",age,weight);
}
-(void) setAge:(int) a{
age = a;
}
-(void) setWeight:(int) w{
weight = w;
}
#end
int main(int argc, char *argV[]){
Person *test;
test = [test init];
[test setAge:25];
[test setWeight:75];
[test print];
return 0;
}
When I run the program the output console disappears as shown in the top right hand corner. When I display the output console by explicitly clicking on the same, I can see the program exited with code 0(successful output?) but NSLog not printed.
Let me know if I am doing some rookie mistake :)
test = [test init];
needs to be:
test = [[Person alloc] init];
You always need to alloc then init. And you need to specify the class name
You need two write:
Person *test = [[Person alloc] init];
You need this code.
Person *test = [Person new ];

custom class not implementing itself when i use alloc/init or new in objective-c

i am writing my first custom class in objective-c and when i am trying to implement an instance of my custom class i get warnings that say "car may not respond to '+alloc'" and "car may not respond to '+init'" and if i use new instead i get the same warning that it may not respond to new. does anyone know why this might be? here is my code:
#import <Foundation/Foundation.h>
#interface Car
{
NSString *color;
NSString *make;
int year;
}
- (void) print;
- (void) setColor: (NSString *) c;
- (void) setMake: (NSString *) m;
- (void) setYear: (int) y;
#end
#implementation Car
- (void) print
{
NSLog(#"The $d Ford %# is $#.", year, make, color);
}
- (void) setColor: (NSString *) c
{
color=c;
}
- (void) setMake: (NSString *) m
{
make=m;
}
- (void) setYear: (int) y
{
year=y;
}
#end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Car *car;
car = [Car alloc];
car = [Car init];
[car setColor:#"blue"];
[car setMake:#"Bronco"];
[car setYear:1992];
[car print];
[car release];
[pool drain];
return 0;
}
Looks like you have two problems; one, you should probably explicitly subclass NSObject. Two, you aren't calling init on the allocated memory... try the following changes:
#interface Car : NSObject
Car *car = [[Car alloc] init];
You should also look into using properties for your "setColor", "setMake", etc. because you aren't retaining or releasing those strings properly, and they will leak and cause an ugly mess. It really helped me to turn on the static analyzer (you can set this in the project settings, or press Apple-Shift-A to build with the analyzer enabled).
EDIT:
OK, so the accepted "answer" post has memory issues... and it doesn't look like it's going to get fixed, so here is the whole thing... properly done:
#import <Foundation/NSObject.h>
#import <Foundation/Foundation.h>
#interface Car : NSObject
{
NSString *color;
NSString *make;
int year;
}
#property (retain,readwrite) NSString * color;
#property (retain,readwrite) NSString * make;
#property (assign,readwrite) int year;
- (void) print;
#end
#implementation Car
#synthesize color;
#synthesize make;
#synthesize year;
- (void) print
{
NSLog(#"The %d Ford %# is %#.", year, make, color);
}
- (void) dealloc
{
if (color)
[color release];
if (make)
[make release];
[super dealloc];
}
#end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Car *car = [[Car alloc] init];
car.color = #"blue";
car.make = #"Bronco";
car.year = 1992;
[car print];
[car release];
[pool drain];
return 0;
}
If you want to see the PROBLEM with the accepted answer, try this modified main function (using the rest of his post):
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Car *car = [[Car alloc] init];
// Let's pretend we are getting a string from somewhere else:
NSFileHandle *fileHandle = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData;
NSString *inputString;
printf("Type the color: ");
inputData = [fileHandle availableData];
inputString = [[NSString alloc] initWithData: inputData encoding:NSUTF8StringEncoding];
[car setColor:inputString];
[car setMake:#"Bronco"];
[car setYear:1992];
// This works:
[car print];
// But now, the place that gave us the string releases it:
[inputString release];
// UT OH! Danger Will Robinson!
[car print];
[car release];
[pool drain];
return 0;
}
You can use the exact same main method with my posted code, and it will work without an error because the Car class will retain the string, and release it when it's done. (and the setXXX: is also valid when using properties)
EDIT: Compiler outsmarted me when I tried to demo the EXEC_BAD_ACCESS using a static string... ha.
First of all, your Car-class should inherit from NSObject (thats the reason why the +alloc method isnt found)
#interface Car : NSObject
{
NSString *color;
NSString *make;
int year;
}
(void) print;
(void) setColor: (NSString *) c;
(void) setMake: (NSString *) m;
(void) setYear: (int) y;
#end
The "init" method is an instance-method that meens you can only send that message to an object not to a class (Car). The normal way is to send the +alloc message to the class to instanciate an object of that class. then you send this created object the -init message:
Car *car;
car = [Car alloc];
car = [car init];
Or the most convenient way:
car = [[Car alloc] init];
The alloc method creates the object and reserves the memory for it, for that its a CLASS-method because there is no object yet. the init message is then send to the created object.