how to pass string value from one class to another
I just want to know that how to pass the string value from one class to another..
Actually i have two classes.In first class i fetch string value from the array and i just want to use this string value into my second c开发者_Python百科lass.Now i don't know how to pass value between this two classes.Please give me some idea to do that.Should i use some class method to pass the value.But i don't know how to use this class methods.How i create the class methods to set the values from one class and then get the same value from class methods.
Thanks for help
Class1.h:
@interface Class1 : NSObject
{
NSArray *arr;
}
- (NSString *)myString;
@end
Class1.m:
@implementation Class1
- (NSString *)myString
{
return [arr objectAtIndex:0];
}
@end
Class2.h:
@interface Class2 : NSObject
{
}
- (void)methodThatUsesStringFromClass1:(Class1 *)c1;
@end
Class2.m:
@implementation Class2
- (void)methodThatUsesStringFromClass1:(Class1 *)c1
{
NSLog(@"The string from class 1 is %@", [c1 myString]);
}
@end
The simplest way is to define public @property
in class where you want to pass your object, for example, for NSString:
// CustomClassA.h
@interface CustomClassA : NSObject
{
}
@property (nonatomic, retain) NSString *publicString;
@end
// CustomClassA.m
@implementation CustomClassA
@synthesize publicString;
@end
In your sender:
//somewhere defined CustomClassA objectA;
[objectA setPublicString:@"newValue"];
But you should understand what means retain
, @synthesize
and other. Also it is not your current question.
you can use appDelegate.YourStringVaraible =@"store your string";
and then use this YourStringVaraible in any class by using appDelegate.YourStringVaraible
pass the string parameter by overriding the init
method.
Class1.m
@implementation Class1
Class2 *class2 = [[Class2 alloc] initWithString:myString];
...
@end
Class2.h
@interface Class2 : NSObject
{
NSString *string2;
}
@end
Class2.m
-(id) initWithString:(NSString*)str {
self = [super init];
if(self) {
string2 = str;
}
return(self);
}
精彩评论