加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中将字符串附加到NSMutableString

发布时间:2020-12-14 04:45:27 所属栏目:百科 来源:网络整理
导读:我在Objective C中找到了我的问题的答案,但在 Swift中找不到它.如何在将字符串值添加到NSMutableString方面使下面的代码工作?它抛出“仅为抽象类定义的长度”错误. 此代码旨在解析xml提要并将其写入NSMutableDictionary() var ftitle = NSMutableString?()f
我在Objective C中找到了我的问题的答案,但在 Swift中找不到它.如何在将字符串值添加到NSMutableString方面使下面的代码工作?它抛出“仅为抽象类定义的长度”错误.

此代码旨在解析xml提要并将其写入NSMutableDictionary()

var ftitle = NSMutableString?()
func parser(parser: NSXMLParser!,foundCharacters string: String!) {
if element.isEqualToString("title") {
        ftitle?.appendString(string)
    }
}

编辑:这里有更多背景;

element是NSString,在DidStartElement期间分配给解析器中的elementName.在这段代码中,我通过元素捕获了feed内容的“标题”.

我有一个NSMutableDictionary(),其中包括不同的NSMutableString(),如ftitle.这段代码是将字符串添加到ftitle,这是NSMutableString,然后它将成为NSMutableDictionary的一部分,最后我将读取它写在我的tableviewcells中

这是didStartElement方法:

func parser(parser: NSXMLParser!,didStartElement elementName: String!,namespaceURI: String!,qualifiedName qName: String!,attributes attributeDict: [NSObject : AnyObject]!) {
    element = elementName

    if (element as NSString).isEqualToString("item"){
        elements = NSMutableDictionary.alloc()
        elements = [:]
        ftitle = NSMutableString.alloc()
        link = ""
        fdescription = NSMutableString.alloc()
        fdescription = ""
    }
}

解决方法

ftitle = NSMutableString.alloc()

不是分配空字符串的正确方法.它分配了
NSMutableString没有初始化它. NSMutableString是一个类
群集,所以这可能会导致各种奇怪的错误.

在Swift中,你就是这么做的

ftitle = NSMutableString()

或者干脆

ftitle = ""

出于同样的原因,

elements = NSMutableDictionary.alloc()

是错的,应该是

elements = NSMutableDictionary()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读