首页 \ 问答 \ iOS中的范围和线程(Scope and threading in iOS)

iOS中的范围和线程(Scope and threading in iOS)

我对iOS中的Web服务调用和线程都不熟悉。 我的应用程序中有一个包含tableview控件的ViewController 。 我使用通过JSON Web服务获得的数据填充表。 JSON Web服务在其自己的线程上调用,在此期间我填充了NSArrayNSDictionary

我的数组和字典似乎超出了范围,因为我的NSLog语句为数组计数返回零,即使在fetchedData中数组已完全填充。

有人可以解释为什么我的数组和字典对象在线程外是空的吗?


- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *serviceEndpoint = [NSString stringWithFormat:
                                 @"http://10.0.1.12:8888/platform/services/_login.php?un=%@&pw=%@&ref=%@",
                                 [self incomingUsername], [self incomingPassword], @"cons"];
    NSURL *url = [NSURL URLWithString:serviceEndpoint];
    dispatch_async(kBgAdsQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });

    NSLog(@"ARRAY COUNT: %d\n", [jsonArray count]);
}

-(void)fetchedData:(NSData*)responseData{
    NSError *error;
    jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    jsonArray = [[jsonDict allKeys]sortedArrayUsingSelector:@selector(compare:)];
    for(NSString *s in jsonArray){
        NSLog(@"%@ = %@\n", s, [jsonDict objectForKey:s]);
    }
}

I am kind of new to web service calls and threading in iOS. I have a ViewController in my app that contains a tableview control. I am populating the table with data obtained via a JSON web service. The JSON web service is called on its own thread, during which I am populating an NSArray and NSDictionary.

My array and dictionary seem like they are going out of scope since my NSLog statement is returning zero for the array count even though while in fetchedData the array is fully populated.

Can someone offer an explanation as to why my array and dictionary objects are empty outside of the thread?


- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *serviceEndpoint = [NSString stringWithFormat:
                                 @"http://10.0.1.12:8888/platform/services/_login.php?un=%@&pw=%@&ref=%@",
                                 [self incomingUsername], [self incomingPassword], @"cons"];
    NSURL *url = [NSURL URLWithString:serviceEndpoint];
    dispatch_async(kBgAdsQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });

    NSLog(@"ARRAY COUNT: %d\n", [jsonArray count]);
}

-(void)fetchedData:(NSData*)responseData{
    NSError *error;
    jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    jsonArray = [[jsonDict allKeys]sortedArrayUsingSelector:@selector(compare:)];
    for(NSString *s in jsonArray){
        NSLog(@"%@ = %@\n", s, [jsonDict objectForKey:s]);
    }
}

原文:https://stackoverflow.com/questions/16170779
更新时间:2022-02-05 20:02

最满意答案

哇,真是个噩梦。 我找到了罪魁祸首。

我创建了一个TypeConverter来将List<Integer>转换为字符串(并返回),以便它可以存储在房间DB中的单个列中,而无需修改现有的DTO。 但是,当我切换到使用Long类型作为ID时,我无法在转换器中转换下面的单个泛型参数; 仔细查看以下代码:

public class IdsListConverter {

    @TypeConverter
    public List<Long> idsFromString(String value) {
        Gson gson = new Gson();
        if (value == null || value.isEmpty()) {
            return null;
        } else {
            Type resultType = new TypeToken<List<Integer>>(){}.getType();
            return gson.fromJson(value, resultType);
        }
    }

    @TypeConverter
    public String idsToString(List<Long> ids) {
        if (ids == null) {
            return null;
        } else {
            Gson gson = new Gson();
            return gson.toJson(ids);
        }
    }

}

Wow, what a nightmare. I have found the culprit.

I had created a TypeConverter to turn a List<Integer> to into a string (and back) so that it can be stored in a single column in the DB in room without having to modify the existing DTOs. However, when I switched over to using Long types as IDs, I failed to convert a single generic argument below in the converter; look carefully at the following code:

public class IdsListConverter {

    @TypeConverter
    public List<Long> idsFromString(String value) {
        Gson gson = new Gson();
        if (value == null || value.isEmpty()) {
            return null;
        } else {
            Type resultType = new TypeToken<List<Integer>>(){}.getType();
            return gson.fromJson(value, resultType);
        }
    }

    @TypeConverter
    public String idsToString(List<Long> ids) {
        if (ids == null) {
            return null;
        } else {
            Gson gson = new Gson();
            return gson.toJson(ids);
        }
    }

}

相关问答

更多
  • d={} new_list = [d[i] for i in values if d.setdefault(i,len(d)+1)] d={} new_list = [d[i] for i in values if d.setdefault(i,len(d)+1)]
  • 不,没有这样的内置功能。 这是一个天真的实现: let mode = function | [] -> None | xs -> let mostFrequentTwo = xs |> Seq.groupBy id |> Seq.map (fun (n, ns) -> n, Seq.length ns) |> Seq.sortByDescending snd ...
  • 你很亲密! 您需要做的就是使用list.extend而不是list.append : new_list = [] for i in zip(lista, listb): new_list.extend([i[0]] * i[1]) 这将使用您提供的元素(附加每个单独元素)扩展list new_list ,而不是附加完整列表。 如果您需要获得幻想,您可以始终使用itertools函数来实现相同的效果: from itertools import chain, repeat new_list = l ...
  • 你总是会遇到溢出问题,特别是当你有大量的互质数字时。 但是要稍微抵消这一点,你可以像迈克尔建议的那样写a * (b/gcd(a,b)) 。 由于gcd(a,b)是a和b的除数,因此不必担心由于整数除法导致的不准确结果。 You're always going to have overflow problems, especially whenever you have large coprime numbers. But to offset this a little, you can do as Mich ...
  • 通过继承collections.MutableSequence而不是list你可以减少代码。 MutableSequence将根据以下五种方法自动实现所有其他列表方法。 from collections import MutableSequence class IntList(MutableSequence): def __init__(self): super(IntList, self).__init__() self._list = [] def _ ...
  • 这应该工作: <%# Container.DataItem %> This should work: <%# Container.DataItem %>
  • 哇,真是个噩梦。 我找到了罪魁祸首。 我创建了一个TypeConverter来将List转换为字符串(并返回),以便它可以存储在房间DB中的单个列中,而无需修改现有的DTO。 但是,当我切换到使用Long类型作为ID时,我无法在转换器中转换下面的单个泛型参数; 仔细查看以下代码: public class IdsListConverter { @TypeConverter public List idsFromString(String value) { ...
  • 在求和时将元素转换为Long(或BigInt应该那么远): x.view.map(_.toLong).sum 您也可以返回折叠 x.foldLeft(0L)(_ + _) (注意:如果你总结一个范围,也许最好做一点数学,但我明白这不是你事实上的做法) Convert the elements to Long (or BigInt should that go that far) while summing: x.view.map(_.toLong).sum You can also go back t ...
  • 这是一个例子,其中添加的东西来自字典 >>> L = [0, 0, 0, 0] >>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1}) >>> for item in things_to_add: ... L[item['idx']] += item['amount'] ... >>> L [0, 1, 1, 0] 以下是从另一个列表添加元素的示例 >>> L = [0, 0, 0, 0] >>> things_ ...
  • 你已经重新发现了维基百科所谓的计数排序 ,这是一种非常简单的分布排序算法。 它是您的数据集的最佳算法:它在O(N + k)时间内运行(N是记录数,k是不同键的数量),使用O(k)附加存储,并且具有非常低的系数。 You've rediscovered what Wikipedia calls counting sort, a very simple distribution sorting algorithm. It is the optimal algorithm for your data set: i ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)