Understanding Errors in the stringByAppendingPathComponent

Asked 2 years ago, Updated 2 years ago, 30 views

An error occurs when configuring the path.How should I rewrite this?If there is anyone who can tell me, please let me know.

Regarding the update of the questionnaire, the return value of getCacheDirectory() is NSSstring.

funcgetFileURL()->NSURL{
    let path=getCacheDirectory().stringByAppendingPathComponent(fileName)// This is where the error occurs.

    let filePath = NSURL (fileURLWithPath:path)

    return filePath
}

swift

2022-09-29 22:40

2 Answers

The error message appears in the 'stringByAppendingPathComponent' is unavailable:Use
URLByAppendingPathComponent on NSURL install.

Then, the return type of the function getCacheDirectory() is probably String.
Use dynamicType to verify the type (class name).(The verification code below and the results were executed in Xcode 7.0.1, Swift 2.0.)Older versions may not produce the same results.)

print(getCacheDirectory().dynamicType)

If the return type is NSString, you should see _NSCFSString , where _NSCFSString is one of the NSString cluster clusters.
If the return type is String, print String.


2022-09-29 22:40

getCacheDirectory() implementation is unknown, but

func getCacheDirectory()->NSString{
    return NSSearchPathForDirectoriesInDomains (.CachesDirectory, .UserDomainMask, true).last!
}

You can normally use stringByAppendingPathComponent if it is something like .

let path=(getCacheDirectory() as NSSstring).stringByAppendingPathComponent(fileName)

You can cast it as shown in , but it is preferred to convert it to NSURL.

Swift has an implicit translation between String and NSString, but the limitations gradually increase as it goes through the version.

The reason is that Swift's String is a value type, whereas Objective-C's NSString is a reference type.

Because NSString is a cluster, there are multiple subclass implementations, but they bridge all of them, so some subclass implementations of NSString can cause unexpected performance degradation.

In Swift 1.2 to 2.0, using a group of methods that handle path strings such as stringByAppendingPathComponent (where the implementation is thought to be in NSPathStore2),

'stringByAppendingPathComponent' is unavailable:Use URLByAppendingPathComponent on NSURL install.

The compilation error now appears.This is a message that should be converted to NSURL and replaced by URLByAppendingPathComponent in order to avoid the above problem, so it would be safe to follow it.


2022-09-29 22:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.