easiest way to access a variable in another class
i declare a variable in one class and want to use that variable in the same class but i want to put data into the variable in a different class. How can i fill a variable from another class?
EDIT:
I have this in one class:
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *aString = [[managedObject valueForKey:@"data"] description];
Then i have this in another class:
NSString *stalklabel = aString;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://news.search.ya开发者_JAVA百科hoo.com/rss?ei=UTF-8&p=%@&fr=news-us-ss", stalklabel, nil]];
Make a property / setter method to set the variable:
In the .h
@property(nonatomic, assign) int myInt;
In the .m
@synthesize myInt;
In your first class create a method that returns that string.
+ (NSString*)dataName {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *aString = [[managedObject valueForKey:@"data"] description];
}
In the second class, call that method.
- (void)whatEverClass {
NSString *stalklabel = [FirstClass dataName];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://news.search.yahoo.com/rss?ei=UTF-8&p=%@&fr=news-us-ss", stalklabel, nil]];
}
The stuff about properties is all true. The missing piece is a way for one class to talk to another. I do this all the time as follows:
Suppose I have a class called "First", and a class "Second". In my "First" class, I want to be able to access the "myInt" varable inside the "Second" class.
I would declare "Second" as such:
@class FirstClass; // Forward Declaration
@interface SecondClass: NSObject {
FirstClass*first;
}
@property (nonatomic,retain) FirstClass *first;
Now, whereever I created secondClass (say in this case it was inside firstClass, but it doesn't have to be), I'd do something like"
SecondClass *second = [[SecondClass alloc] init];
[second setFirst: self];
Then inside "second" code, you can do:
[first setMyInt:123];
精彩评论