Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get each line from an NSString?

If I have an NSString with a text file in it, how do I get an NSArray of NSString with each NSString containing a line of the file.

In 10.5 I did this:

NSArray* lines = [str componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

But that doesn't work in 10.4, and my program needs to work in 10.4.

As well, it needs to work with \r, \n and \r\n line endings.

like image 248
Roland Rabien Avatar asked Dec 05 '08 00:12

Roland Rabien


People also ask

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .

What is NSString objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.


1 Answers

The following code is straight from Apple's documentation regarding paragraphs and line breaks:

unsigned length = [string length];
unsigned paraStart = 0, paraEnd = 0, contentsEnd = 0;
NSMutableArray *array = [NSMutableArray array];
NSRange currentRange;
while (paraEnd < length)
{
    [string getParagraphStart:&paraStart end:&paraEnd
    contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
    currentRange = NSMakeRange(paraStart, contentsEnd - paraStart);
    [array addObject:[string substringWithRange:currentRange]];
}

I'm not 100% sure if it will work with 10.4

like image 125
e.James Avatar answered Dec 03 '22 09:12

e.James