开发者

How can I use NSString between classes?

开发者 https://www.devze.com 2023-01-06 13:48 出处:网络
I have tw开发者_JAVA技巧o classes, Class A and Class B, both of them are subclasses of UIViewController.

I have tw开发者_JAVA技巧o classes, Class A and Class B, both of them are subclasses of UIViewController.

I class A I have an NSString and I want to use this NSString in class B.

ClassA.h:

@class ClassB;
@interface ClassA : UIViewController {
   ClassB *classB;
   NSString stringA;
}
@property (nonatomic, retain) ClassB *classB;
@property (nonatomic, retain) NSString *stringA;

@end

ClassA.m:

stringA = [NSString stringWithString:webView.request.URL.absoluteString];

ClassB.h:

@class ClassA;
@interface ClassA : UIViewController {
   ClassB *classA;
   NSString stringB;
}
@property (nonatomic, retain) ClassB *classA;
@property (nonatomic, retain) NSString *stringB;

@end

ClassB.m:

- (void)viewWillAppear:(BOOL)animated { 
self.stringB = classA.stringA;
}

Of course I did #import for both classes. For some reason I always get NULL I classB for stringB.

Thanks!


The following aren't clear:

  • is mainViewController actually an instance of ClassA?
  • is classA even an instance of ClassA, as you've declared it an instance of ClassB?
  • what is your real code, as the things you've pasted here don't compile?
  • when in the ClassA object's lifecycle do you initialise stringA?
  • did that occur before you tried to use it in your ClassB object?


I would like to comment one thing you have high probability of RetainLoop, while ClassA retains ClassB and ClassB retains ClassA. When do they release?

Second thing, in:

ClassA.m:

stringA = [NSString stringWithString:webView.request.URL.absoluteString];

change to:

self.stringA = [NSString stringWithString:webView.request.URL.absoluteString];

while object returned by [NSString stringWithString:] is set to autorelease, and you need to retain it to be sure that you have valid instance of string.

Please provide more code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号