我创建了一个从服务器获取数据的方法,一切正常,除非我尝试将字符串设置为例如UILabel
或UITextView
,没有任何显示和更改!这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self getDataFromURL:@"http://somesites.net/panel/services?action=events&num=1"
setTitle:_eTitle1.text image:_eImage1 description:_eNews1.text];
}
获取数据:
-(void)getDataFromURL:(NSString*)url setTitle:(NSString*)eTitle
image:(UIImageView*)eImages description:(NSString*)eDescriptions {
NSURL *URL = [NSURL URLWithString:url];
NSError *error1;
NSString *strPageContent = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:&error1];
strPageContent = [strPageContent gtm_stringByUnescapingFromHTML];
if ([strPageContent rangeOfString:@"<plist version=\"1.0\">"].location != NSNotFound) {
NSRange range = [strPageContent rangeOfString:@"<plist version=\"1.0\">"];
strPageContent = [strPageContent substringWithRange:NSMakeRange(range.location+range.length, strPageContent.length-(range.location+range.length))];
strPageContent = [strPageContent stringByReplacingOccurrencesOfString:@"</plist>" withString:@""];
}
NSError *error = nil;
NSDictionary *dict = [XMLReader dictionaryForXMLString:strPageContent options:XMLReaderOptionsProcessNamespaces
error:&error];
if ([dict count]>0) {
NSDictionary *dictInner = [dict objectForKey:@"dict"];
NSArray *arrValues = [dictInner objectForKey:@"string"];
NSString * strTitle = [[arrValues objectAtIndex:0] objectForKey:@"text"];
NSString *strImage = [[arrValues objectAtIndex:1] objectForKey:@"text"];
NSString * strDescription = [[arrValues objectAtIndex:2] objectForKey:@"text"];
eTitle = strTitle;
eDescriptions = strDescription;
// [eImages setImageWithURL:[NSURL URLWithString:strImage]
// placeholderImage:[UIImage imageNamed:@"loadingPad.jpg"]];
NSLog(@"Title: %@ | Image: %@ | Desc: %@",eTitle,strImage,eDescriptions);
}
}
编译器给了我正确的信息!但是这些字符串无法设置为我的标签,如果我将我的标签字符串放入其工作的方法中! :
_eTitle1.text = strTitle ;
答案 0 :(得分:1)
这是完全正常的:当您将“text”对象传递给方法时,您将指针传递给它。直接为其分配另一个NSString对象将只分配一个新指针。为了对字符串产生副作用,你必须使用NSMutableString,但是UILabel只有一个不可变的NSString用于text属性。因此,唯一的解决方案是传递UILabel或在方法内传递初始化的空可变字符串,通过[eTitleText setString:strTitle]
更改内容,然后在方法外部将其分配给UILabel text
属性。
所以,要么改变这样的方法(就像你已经做的那样):
-(void)getDataFromURL:(NSString*)url setTitle:(UILabel*)eTitle
image:(UIImageView*)eImages description:(NSString*)eDescriptions {
...
eTitle.text = strTitle;
...
并像这样使用它:
- (void)viewDidLoad
{
[super viewDidLoad];
[self getDataFromURL:@"http://somesites.net/panel/services?action=events&num=1"
setTitle:_eTitle1 image:_eImage1 description:_eNews1.text];
}
或者你可以采取另一种方式:
-(void)getDataFromURL:(NSString*)url setTitle:(NSMutableString*)eTitle
image:(UIImageView*)eImages description:(NSString*)eDescriptions
...
[eTitle setString:strTitle];
...
并像这样使用它:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableString *titleText = [NSMutableString new];
[self getDataFromURL:@"http://somesites.net/panel/services?action=events&num=1"
setTitle:titleText image:_eImage1 description:_eNews1.text];
eTitle1.text = titleText;
}