Jacob
Jacob

Reputation: 1459

Passing NSString between classes

this is something I have always had confusion about

I never can seem to find a good explanation, i understand inheritance, but from what i learned that is between the master class and the sublasses of them...What if i want to pass a NSString to another class thats not a subclass of the other

Heres a example:

class1.h

@interface class1 : UIViewController{
NSString *string
}
@property (nonatomic, retain) NSString *string
@end

class1.m

@implementation class1
@synthesize string;
-(void)viewDidLoad{
 string = @"IM A STRING AHHH";
 }

Now lets say i want to pass that string with what its equal to to another class

class2.h

#import "class1.h"
@interface class2 : UIViewController{


}

@end


class2.m

@implementation class2 

//i want to use the NSString in here, how do i do that?

Thanks, Jacob

Upvotes: 1

Views: 737

Answers (4)

Baby Groot
Baby Groot

Reputation: 4279

First of all use [string retain]; in class 1. Then, in class 2, import class1. make object of class 1 say cls1. and you can access it by cls1.string;

Upvotes: 2

Govind
Govind

Reputation: 2348

If class 2 is loading from class 1 you can send the value as parameters.

-(id)initwithParameters:(NSString *)parameter
{

    if(self == [super init])
    {
        // access the paramenter and store in yo u avariable    
    }
    return self;

}

In class 1

[[class 2 alloc]initwithParameters: ] 

Upvotes: 1

Manlio
Manlio

Reputation: 10865

You can create an instance of class1 and then you can access string simply calling

 [instance string];

or

 instance.string

If you don't want to create an instance of class1 you may define a method such as

+(NSString*)getString;

and then call it from class2

[class1 getString];

Upvotes: 1

Shrey
Shrey

Reputation: 1977

Smiriti's answer is right...

what else you can do is..

overrirde the init method and pass your NSString as a parameter and use it.

Upvotes: 1

Related Questions