FAQ Database Discussion Community


Get position of NSString in string - iOS

ios,objective-c,string,nsstring,nsurl
I am developing an iOS app and one of the things I need to do it to go over URLs and replace the first protocol section with my own custom protocol. How can I delete the first few characters of a NSString before the "://"? So for example I need...

Solution for if else and NSString statement

objective-c,if-statement,nsstring
What NSString do I put for return? The answer I am looking for is 1 cheese OR 2 cheeses - (NSString *) numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount { if (cheeseCount == 1) { /* WORK HERE, ASSUMING THERE IS 1 CHEESE */ NSString *phrase = [NSString stringWithFormat:@"%ld", (long)cheeseCount]; NSLog(@"%@ cheese", phrase); } else {...

Set Default values of NSString properties automatically

ios,objective-c,nsstring,objective-c-runtime
I have many bean/data classes in my code which I'm using to convert to JSON for network communication purposes. The issue is, if there's a NSString property in my class I want to set its default value to empty string @"" rather than nil. One option I have is this...

Displaying a string with multiple attributes in a label

ios,nsstring,uilabel,nsattributedstring
I need to display a string which will change every second. For example : View will refresh in 10 sec View will refresh in 09 sec View will refresh in 08 sec View will refresh in 07 sec .. View will refresh in 0 sec The above string needs to...

'NSString' is not a subtype of 'UILAbel' in Swift View Controller

ios,iphone,swift,nsstring
I'm currently reading the book, Beginning iPhone Development with Swift and having some trouble in the third chapter's exercise. It basically has you created two buttons (both linked to the same action) and a label that has its text change depending on which button you press. I've followed the example...

NSString stringWithFormat “implicit conversion loses integer precision”

objective-c,nsstring,implicit-conversion,stringwithformat
Im trying to save a high score using HighScore = [[NSUserDefaults standardUserDefaults]integerForKey:@"ScoreSaved"]; Intro3.text = [NSString stringWithFormat:@"HighScore: %i", HighScore]; it says : "implicit conversion loses integer precision, NSInterger(aka long) to int -(void)EndGame { if (ScoreNumber > HighScore){ HighScore = ScoreNumber; [[NSUserDefaults standardUserDefaults]setInteger:HighScore forKey:@"ScoreSaved"]; } this is my first game and i...

How to get specific strings from NSString?

ios,objective-c,search,nsstring,nsarray
I have a string such as: Sodium Nitrite E250 is a food additive that gives cured meats, such as ham E103, bacon, hot dogs, frankfurters, smoked fish E1255 corned beef, their characteristic red colour and flavour. I need to get an NSArray of elements: E250, E103, E1255 from text above...

Unable to read contents of .doc file in iOS

ios,nsstring,nsattributedstring
I am trying to read in arabic text that I have contained inside of a .doc file, and use it in my app. Unfortunately, the only way I am able to retrieve the text is if I convert the document into .txt file. Here is the code I have: NSError...

Highlighting some text in a TextField differently

ios,objective-c,iphone,nsstring,uitextfield
I'm creating a recipe by ingredient app. When I type the ingredients on the textfield and then press the find a recipe button it downloads recipes with those typed ingredients but it displays additional ingredients on the label and what I want to do is to display the label with...

How to spliit a NSString in iOS [duplicate]

ios,nsstring
This question already has an answer here: Split an NSString to access one particular piece 6 answers I have a NSString like this. 00:03:45 I want to get only this 03:45 part and show in a UILabel How can I do that? Please help me Thanks...

Matching a string against multiple patterns

objective-c,nsstring
I have a question regarding the style of a solution for a pretty simple problem. I have a program that matches a list of file names against a number of patterns. If the file name matches a pattern, the file is renamed and a counter is incremented. Currently I'm matching...

Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?

ios8,nsstring,uilabel,uifont
I have found that a call to boundingRectWithSize is extremely incorrect, missing an entire additional line, when called with NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody]. However, using the font [UIFont fontWithName:@"Helvetica Neue" size:17.f], it is just fine. Here is test code showing the bug: - (void)viewDidLoad { [super viewDidLoad]; NSString *measureText =...

NSLog prints a string different to the NSString with format

objective-c,osx,nsstring,nslog
This is something that I'm truly baffled by: when I initialize a string with format with two different variables like this Order *o = [orders objectAtIndex:i]; NSString *line = [[NSString alloc] initWithFormat:(@"%@;%@\n", [o _length], [o _amount])]; and then print it out with NSLog(@"%@", line); it shows up like this: tableviewtest[4812:123250]...

Value of NSString returns null, but unsure why?

ios,objective-c,nsstring
I've set the value of my NSString called "fid" to responseObject (see below). responseObject returns the data I want when NSLog'd, but for some reason when I NSLog fid further down, it's empty. Am I missing something? See code: .h @property (nonatomic, assign) NSString *fid; .m [DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation,...

NSString thinks it is null

ios,objective-c,nsstring
I have run in to issue like that My NSString has a weird behaviour after this: NSMutableArray *_keys = [[NSMutableArray alloc]initWithArray:[[_currentContact.phoneNumbers allKeys]mutableCopy]]; NSString *fail = [_keys objectAtIndex:0]; my NSString *fail (in debugger) says it is null but when I do print it, it has the proper string. I think it...

extract UIButton object from NSString

ios,objective-c,uibutton,nsstring
I want to hide already created UIButton object of same name as contents of string myBtnName NSString *str=@"first"; NSString *myBtnName=[str stringByAppendingString:@"Btn"]; myBtnName is (NSString ) and has value of @"firstBtn"... How do i make it (UIButton) firstBtn ?... Please Help...

How to strip special characters out of string?

regex,string,swift,nsstring,nscharacterset
I have a set with the characters I allow in my string: var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ") I want to strip any other characters from a string so two unformatted data can be considered equal, like this: "American Samoa".lowercaseString == "american_samoa1".lowercaseString the lowercase version of these transformed strings would be...

accessing old values of immutable strings

objective-c,nsstring,immutability
So I wrote this code: NSString *str1=@"string 1"; NSString *str2=@"string 2"; NSLog(@"str2 is: %@", str2); str2=[str1 stringByAppendingString:str2]; NSLog(@"str2 is: %@",str2); and it gave the following output: 2015-03-01 17:11:16.600 er[956:32910] str2 is: string 2 2015-03-01 17:11:16.601 er[956:32910] str2 is: string 1string 2 so str2 now points to different location in memory....

NSJSONSerialization.JSONObjectWithData changes field type

objective-c,swift,nsstring,nsdictionary,nsdata
I'm getting the following JSON response from the server: { "userId":"123456789", "displayName":"display name" } When I use NSJSONSerialization.JSONObjectWithData and then prints the result NSDictionary I see in the console the following: userId = 123456789 displayName = "display name" Why do JSONObjectWithData changes the userId field type from String to a...

Convert AnyObject to NSString to Swift String

string,swift,nsstring
I am trying to understand why I cannot get a swift String from my dictionary type of AnyObject. If I do a println(fileCreationDate) it works, but I need an actual string of some kind to work with. So when I try to convert it to an NSString (because it is...

Matching stand-alone substrings in Swift

ios,regex,string,swift,nsstring
I want to check if a string is part of another string but only as a standalone term, not as part of another word. I am working in Swift. E.g. Here's what I would expect checking for "mon" "Mon" true "mon" true " Mon" true " Mon " true "Monday"...

How I can avoid caching of NSString instances in Objective-C runtime?

objective-c,nsstring,osx-yosemite
Objective-C can to cache short strings. If you run modified code from original question, you'll get result, that strings is same (one instance) (Build for OS X Yosemite). How to avoid this behaviour? NSString* value1; NSString* value2; __weak NSString* weakValue1; __weak NSString* weakValue2; NSMutableString* resultText = [NSMutableString new]; @autoreleasepool {...

isEqualToString always returns False

ios,objective-c,nsstring
A little background here before I get started, basically we are looking to compare a UDP response with a string stored in Parse's database for our app. This issue is that I can't seem to get the strings to be considered equal by the isEqualToString function. Here's the code I...

NSString sizing does not account for Greek breathing marks

ios,unicode,nsstring,wkinterfacelabel
I've got an app that displays Greek text. I use the Cardo font for good display. In working on an AppleWatch extension and app, it was pointed out to me that some of the special characters are being cut off. This is how some example text should look (screenshot from...

Swift: Parsing Json string and populating information into a dictionary

json,swift,nsstring,nsdictionary
I'm currently learning about web services in Swift. I have this URL that shows recent earthquakes and other information regarding it. The code at the bottom is what I have so far, once I run it, it NSLogs a string in JSON format from the URL. Here are 3 records...

Converting string to date with NSDateFormatter

ios,objective-c,nsstring,nsdateformatter
Im trying to convert this string '2015-05-08T09:44:25.343' format to date 'dd/MM/YYYY' format What I`m doing wrong? my date comes Nil. // convert 2015-05-08T09:44:25.343 to dd/MM/yyyy NSString *str = @"2015-05-08T09:44:25.343"; NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; NSDate *date = [dateFormat dateFromString:str]; NSLog(@"%@",date); NSString *convertedString = [dateFormat stringFromDate:date]; NSLog(@"%@", convertedString); ...

split NSString into NSArray in ios

ios,objective-c,nsstring,nsarray
i'm trying to split NSString to NSArray.String like this: @"text,image". And I am splitting it like this: arrayAnsType = [self.strAnsType componentsSeparatedByString:@","]; NSLog(@"Terms array %@",arrayAnsType); But output like this: ( "(\n \"text", "image\"\n)" ) ...

Drawing artifacts when drawing a NSString in a NSButton

cocoa,nsstring,drawrect,nsimage,nsbutton
I am using drawRect to draw a NSString inside a custom view, which is a subview of NSButton. The drawRect of the NSButton is also drawing an NSImage, which appears to the be the problem. If I remove the drawRect code for the NSImage, it no longer happens (but then...

Xcode Property Not Retaining Value

ios,objective-c,xcode,properties,nsstring
I have a view controller called LoginWindowViewController.h that declared a property called usernameTextField: @property (strong, nonatomic) IBOutlet UITextField *usernameTextField; A string called James is associated to this TextField. I then import another view controller,FirstViewController.h into my LoginWindowViewController.m and I also imported LoginWindowViewController.h into FirstViewController.m . In my FirstViewController.h there is...

Edit contents of NSMutableArray who's name is stored in contents of NSString

ios,arrays,nsstring,nsmutablearray
I have a function that accepts NSString variable in parameters and appends Array at the end which gives it the name of array already defined in class. How can i edit that array ? -(void) editArray:(NSString*)str{ //suppose str value is first NSString* myArrayName = [str stringByAppendingString:@"Array"]; //firstArray myArrayName contains the...

Set UIControl's font to uppercase [duplicate]

string,cocoa,cocoa-touch,nsstring,uppercase
This question already has an answer here: Capitalize or change case of an NSString in Objective-C 2 answers How do I set this to be uppercase? - (void)drawSegmentedControl { HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"First", @"Second", @"Third"]]; segmentedControl.font = [UIFont fontWithName:@"Helvetica Neue" size:16]; } ...

Debugging code:: How to colors lines in CGContext?

swift,nsstring,cgcontext,quartz-core
The following code has an problem, for some reason the radial lines are being drawn black when they should be drawn in UIColor.yellowColor() import UIKit import QuartzCore let π:CGFloat = CGFloat(M_PI) class CircularPlotView:UIView { var lineWidth:CGFloat = 1.5 { didSet { setNeedsDisplay() } } var edgeColor:UIColor = UIColor.yellowColor() { didSet...

Using a regex to remove a specific #tag in Objective-C

ios,objective-c,regex,nsstring
I am trying to parse a string in Objective-C to delete an exact match of a specific #tagged word. I can create a regular expression and delete a specific word without issue, but when I try to remove a string with a leading "#" it's not working. Here's my code:...

Swift NSString to Int conversion issues

swift,command-line,terminal,nsstring,integer
First off, I'm fairly new to programming and trying to learn Swift, though I've worked with python and perl in the past. I'm creating a simple prime number command line application. The program runs correctly when I provide the arguments for the functions, but causes consistently incorrect outputs when I...

Connect this NSSting with a String Variable

ios,objective-c,nsstring
All I want is to change every time the NSString townLocation. Because I take data from an API and I don't want to create different API for different location. Also I know that the "+" that I put on the link is not correct and there is not such think...

Removing Specific Characters from NSString

ios,objective-c,nsstring
For example if i had a string like NSString *myString = @"A B C D E F G"; and I want to remove the spaces, and get a string out like "ABCDEFG". I could use NSString *stringWithoutSpaces = [myString stringByReplacingOccurrencesOfString:@" " withString:@""]; However, for my application I am loading in...

Converting the NSData returned from an HTTP request in Swift to a String

xcode,string,swift,nsstring,nsdata
I have some code that makes an HTTP request, then calls a function with the data, response, and error results. This function then tries to call a function, handler, that takes a Swift String as its sole argument. I have tried to convert the NSData object (data) returned from the...

Delete text after #example iOS

ios,objective-c,nsstring,nsarray
How can I erase a part of NSString or NSArray after a word, for example #gallery-1 or after two "skip lines" ? And is it possible to delete a sentence that appears every time ? I would like to erase all the text after #gallery-1 or after 2 skip lines...

Xcode - String passed to second ViewController through segue returns null

ios,objective-c,xcode,nsstring,segue
I'm trying to pass an NSString from ViewController to secondViewController, but the value returns null. I'm using Storyboards and a present modally segue that fires when the selectDateButton is pressed. The user selects a date using a UIDatePicker, the value is then formatted to MM/dd and put into an NSString...

Remove all non-english characters from NSString

ios,objective-c,nsstring
I'm using Foursquare's API to retrieve some attraction names. The problem is, for certain cities (like Cairo, Moscow, Beijing) the English name of the attraction is appended to the name in the language of the country, so for example an attraction in Cairo will look like this: Wekalet Al-Ghouri Arts...

Convert NSString with octal numbers to decimal int

iphone,nsstring,octal
I have an NSString with octal numbers: NSString* octal = @"247"; I'd like to convert this to an integer in base 10. If this were a hex number I could use NSScanner scanHex method, but there is no scanOct... Thanks!...

How to detect whether a NSString contains one capital letter or not

ios,objective-c,nsstring
I have a textField where I am entering password. Can anyone please tell me how can I check the text that I am entering contains one capital letter or not? I have gone through web but failed to get what exactly I am wanting. Thanks in advance. This is where...

Facing crash to check special character in NSMutableAttributedString

objective-c,iphone,nsstring,nsmutableattributedstring
I have a NSString stored in cell.lblTitle.text. I am converting this NSString to NSMutableAttributedString with following code. text = [[NSMutableAttributedString alloc] initWithData:[cell.lblTitle.text dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil]; [text setAttributes:@{NSFontAttributeName:labelFont} range:NSMakeRange(0, [text length])]; [text...

Replace stretches of spaces and newlines with just a space in a string

ios,objective-c,nsstring
I was wondering if there is a library or easy way that allows me to take an NSString and replace any stretch of '\n' and spaces that are strung together with just a single space? (included in this, I also just want to replace all occurrences of '\n' by itself...

Cannot invoke 'UTTypeEqual' with an argument list of type '(CFString!, CFString!)'

string,swift,types,nsstring,cfstring
How do I get this to compile? On the second line of this function: func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as! CFString! if UTTypeEqual(mediaType, kUTTypeJPEG) { println("jpg") } } I get the compilation error: Cannot invoke 'UTTypeEqual' with an argument list of type...

How to style the NSString using CSS?

css,objective-c,nsstring
I have a dictionary project using database. I want to style the result so that it can be separated lines, have difference colors etc. Example: Song ///this line will be blue color with strong text N. // this line will be black color with strong text うた // this line...

incompatible pointer types sending 'nsnumber *' to parameter of type 'nsstring *'

ios,objective-c,parse.com,nsstring,nsnumber
I am trying to have an alert box show a randomly generated number, but no matter how I play around, I haven't gotten it working yet and I am still searching around the web. Here's what I have: ticketNumber = [NSNumber numberWithInt:arc4random() %100000]; PFObject *people = [PFObject objectWithClassName:@"People"]; people[@"ticket"] =...

NSString value returning before Block has run

ios,objective-c,nsstring
I'm trying to use a value generated inside of a block ("fid") outside of a block. The problem being that the value is being pulled before the block has run, and so the value returns as (null), even though the data is present. Does anyone know how I can make...

How to decrypt nsstring using RNCryptor after conversion from NSData

ios,objective-c,encryption,nsstring,rncryptor
Is there anyway to decrypt a NSString using RNcryptor that has been converted from NSData? I keep getting the unknown header error. Here is what I am doing to encrypt: NSData *data = [@"FeedMeMorePizzaPlease" dataUsingEncoding:NSUTF8StringEncoding]; NSData *encryptedData = [RNEncryptor encryptData:data withSettings:kRNCryptorAES256Settings password:@"pizzaHutIsTheWorst" error:&error]; NSString *encString = [encryptedData base64EncodedStringWithOptions:0]; I then...

NSData to NSString losing data

nsstring,ascii,nsdata,nsstringencoding
I'm attempting to convert a binary file into text, the problem is that a large portion of the file was not encoded in ascii and ends up being special characters. I'm using [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; but am only getting a few characters back in a 20000 byte data block....

SIGTERM when returning NSString

objective-c,osx,cocoa,nsstring,nstask
This is my first real Cocoa project. I wrote a function that takes a NSString as input, uses an NSTask to run an ADB command, and returns the terminal output to an NSString. The code builds fine, but when I press the button to run that function, the app freezes....

Objective C delete last NSString in NSMutableArray

ios,objective-c,nsstring,nsmutablearray
I am trying to get the last NSString from a NSMutableArray, and delete it if it's empty. Here is the code I am using: - (void)viewWillAppear:(BOOL)animated { if ([notes.data length]==0){ [storedText removeLastObject]; } [self.tableView reloadData]; } data is the NSString and storedText is the NSMutableArray. This code deletes the NSString...

(Swift) Print double quotes inside “”?

swift,nsstring,quotes
Can someone please tell me how can I print something in following way "with" double quotes. "Double Quotes"...

Add a nsstring at the end of attributed string in textview iOS

ios,objective-c,nsstring,nsattributedstring
I have a text like "Hello There" which will be a attributed string with red color. Then at the end of that attributed string I want to append a nsstring 'Who are you?' But whenever I append a nsstring, the whole string becomes normal nsstring and the property of the...

NSCFNumber escapedString Error with a NSDictionary

ios,objective-c,nsstring,nsnumber
So I'm getting this error when creating a NSDictionary: DLog(@"hiliteID: %@ | regionID: %@", hiliteID, regionID); if ([hiliteID isKindOfClass:[NSNumber class]]) { DLog(@"hititeID is a number"); } if ([hiliteID isKindOfClass:[NSString class]]) { DLog(@"hiliteID is a string"); } if ([regionID isKindOfClass:[NSNumber class]]) { DLog(@"regionID is a number"); } if ([regionID isKindOfClass:[NSString class]])...

Trying to add data from parse to an NSMutableArray in IOS

ios,objective-c,parse.com,nsstring,nsmutablearray
So, I am able to successfully perform a query of my parse database. This query matches the logged in user with all objects that have the logged in user in the key user. The object I'm querying has keys "email" "firstName" "lastName" "friendUserName" and "phoneNumber" I would like to be...

Calculating the width of a font on screen

ios,objective-c,nsstring
--- CORRECTION: --- I was using the correct method NSString sizeWithAttributes It appears my mistake was using the wrong attributes with it. FontDescriptor attributes have nothing to do with the size attributes used by this method. I should have been using these attributes... Attributes I'm targeting iOS 8. I'm on...

Fail to make Anyobject to NSString in Swift

ios,swift,nsstring
There's an exception when I run it. self.year = value as! NSString Exception: Could not cast value of type '__NSDate' (0x1051bd6a0) to 'NSString' (0x10564d8e0). What am I missing ? var datePicker = ActionSheetDatePicker(title: "Date:",datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(),doneBlock: { picker, value, index in self.year = value as! NSString println("year = \(year)")...

Incompatible pointer types assigning to 'NSArray' to 'NSString'

ios,objective-c,iphone,ios7,nsstring
The RecipeBookViewController.m file is showing a warning in Xcode "Incompatible pointer types assigning to 'NSArray' to 'NSString' can anyone fix this warning. I am developing RecipeBook application from appcoda website from tutorial Tutorial #14 Here is my Recipe.h file #import <Foundation/Foundation.h> @interface Recipe : NSObject @property (strong, nonatomic) NSString *name;...

I am trying to get the string “Mother” to replace the string “string” but I'm getting an error

objective-c,replace,nsstring
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init]; NSString *dog=@"Hotdog? I thought you said hotfrog!"; NSMutableString *mute; mute = [NSMutableString stringWithString:dog]; NSLog(@"%@", mute); [mute setString:@"I am a new string "]; NSLog(@"%@", mute); [mute replaceCharactersInRange: NSMakeRange(11, 12) withString: @"mother"]; NSLog(@"%@", mute); [pool drain];...

Multiline NSString with a character limit per line

ios,objective-c,iphone,nsstring
I want to construct a multi line NSString (for printing purpose) with a character limit per line. Each line should have maximum of 25 characters. Number of lines can be anything based on the length of the string. This is my approach which is not the best I guess. Whats...

Creating a “generated” number from an NSString

ios,nsstring
I'm trying to find a way that I can turn any string into a generated, deterministic number. That is... Each time that the same string is used it will create the same number. Different strings will (probably) create different numbers. For instance, you could add the letter indices in the...

Conversion NSString to const char string[]

ios,objective-c,arrays,nsstring,character
I have one query related conversion I have one NSString object with content some string like below NSString *string = @"do nothing"; Now I am trying to pass string in below code like const char inputString[] = string; Xcode showing error Array initializer must be an initializer list or string...

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring
What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

Typedef statement

objective-c,nsstring
Using typedef statement allow us to create a new type of of data with giving type, for example typedef NSString *String; I also able to treat a new type like NSString: typedef NSString *String; String myString = @"Programming is"; NSLog(@"%@", [myString stringByAppendingString:@"cool"]); My question is - am i not able...

Rotating NSString in Swift

swift,nsstring,calayer,quartz-graphics
I'm trying to do something like the attached image. I thought this page would lead to the answer http://www.informit.com/articles/article.aspx?p=2149190&seqNum=13 or Rotating a NSString in drawRect Drawing rotated text with NSString drawInRect but converting objC to swift is troublesome. I can easily draw my arrows but getting the NSString to rotate...

Using NSMutableAttributedString as a Constant in iOS

ios,swift,nsstring,constants
I just started to learn Swift and came across something I don't understand. In a tutorial the author creates a NSMutableAttributedString within a constant. Later on that constant is altered. What I don't understand is how this is possible without getting any errors. Does NSMutableAttributedString somehow, for lack of a...

Convert NSString to CLLocationCoordinate2DMake using Swift

ios,swift,nsstring
How can I convert NSString to CLLocationCoordinate2DMake. I want to make a marker on map. Here is what I have done but I am getting "NSString is not convertable to CLLocationDegrees" error. for openComplain in openComplains { var lat = openComplain["lat"] as NSString var long = openComplain["lng"] as NSString NSLog("Lat...

NSURL URLWithString is shortening very long strings with an ellipsis “…”, creating invalid NSURL objects

ios,nsstring,nsurl
I am trying to use NSURL URLWithString to create an NSURL object from a potentially very long file path with a very long file name. When I convert the file path to an NSURL object using URLWithString, the path gets shortened and an ellipsis " ... " is put in...

How to add box around NSString inside NSTextView

objective-c,nsstring,nstextview
I'm working on a OS X application and I'm pretty much stuck at this. I have some text inside NSTextView and I would like to put box around some strings (I have ranges for those substrings). Any ideas? Also, perfect solution would be to create something similar that Xcode has,...

Parsing an NSString to find and increment numeric values

objective-c,nsstring
I have an string value. NSString *getAllData = @"0,testing,u,4,u"; Now I want to increment in all the numeric values in the string e.g. @"1,testing,u,5,u" How can this be done?...

NSDictionary and string literal keys

ios,objective-c,nsstring,nsdictionary,nsmutabledictionary
Does using a string literal like @"key" in setObject(id):forKey(id) only work because the compiler optimizes all instances of the string literal to point to the same object? Or does retrieving an object with objectForKey(id) actually compare the string value of the key? What if the NSDictionary was created by an...

SWIFT : Convert String from XLM to NSDate

ios,swift,nsstring,nsdate,nsdateformatter
The following code works on the simulator but doesn't on devices. I tried to replace Z with xx with no luck. Any help appreciated. Thanks. func convertDateStringToNSDate(dateString: String) -> NSDate { var dateFormatter = NSDateFormatter() // Sat, 20 Jun 2015 16:50:20 +0200 dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"...

Extension Property Crashes In NSString Category

ios,objective-c,iphone,nsstring
I have just created an Extension for NSString class inside a Category class #import "NSString+Name.h" @interface NSString(Name) @property (nonatomic, retain) NSString *var; @end But when i am trying to access that private variable inside the category class the app crashes and gives the error. @implementation NSString (Name) - (NSString*)newString{ [self...

How to remove the Additional Content From the NSString in ios

objective-c,nsstring
In my project i have saved the parsed JSON Response in a string,in that string has some additional strings how to remove that i already tried the NSString_stripeHTML File i get same Value only, here is my Strings, First String- "&lt;p&gt;&lt;span style=&quot;color: rgb(84, 84, 84); font-family: arial, sans-serif; font-size: small;...

Trim an NSString Based Upon Number Of Character Occurrences

objective-c,nsstring
I'm trying to trim an NSString after I detect 3 new line instances. (\n). So, this is what I've tried: NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n" options:NSRegularExpressionCaseInsensitive error:&error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [myString length])]; Now, number of matches will always exceed 3, and I want to stop the...

NSString without HTML markup

html,ios,objective-c,nsstring,strip
I have a JSON Data, and I would like to make this JSON Data into NSString without HTML markup. Here is my JSON Data : <p><strong style="font-size: 13px;">13th March</strong></p> <p><span id="fbPhotoSnowliftCaption" class="fbPhotosPhotoCaption" tabindex="0" data-ft="{"tn":"K"}"><span class="hasCaption">Peak is solid 6ft + a bit wild but not a breath of wind around. Rossnowlagh...

What is the best way to convert an array with NSStrings to NSDecimalNumber?

ios,objective-c,nsstring,nsarray,nsdecimalnumber
I have an NSArray with 10 NSStrings inside: myArray ( @"21.32", @"658.47", @"87.32"... ) What's the best way to convert all the strings to an NSDecimalNumber?...

iOS:Placing NSArray in NSString

ios,objective-c,arrays,nsstring,nsarray
I am doing application related to sending data to server and I had array of values and when I am printing that array I getting the out put as below for the code NSArray *dataarray=[NSArray arrayWithObjects:@"2",@"10",@"1",@"4",@"2",@"8",@"2",@"6",@"25",@"11",@"17",@"10",nil]; NSMutableArray *arr=[[NSMutableArray alloc]init]; for (int i=0; i<[dataarray count]; i++) { NSString *stringvar=[dataarray objectAtIndex:i]; NSDictionary...

Access Variable Dynamically

ios,objective-c,nsstring,naming-conventions,dynamic-variables
I have many buttons named like this: @property (weak, nonatomic) IBOutlet UIButton *Round1Num1; @property (weak, nonatomic) IBOutlet UIButton *Round1Num2; @property (weak, nonatomic) IBOutlet UIButton *Round1Num3; @property (weak, nonatomic) IBOutlet UIButton *Round1Num4; @property (weak, nonatomic) IBOutlet UIButton *Round2Num1; @property (weak, nonatomic) IBOutlet UIButton *Round2Num2; @property (weak, nonatomic) IBOutlet UIButton *Round2Num3; @property...

I do not understand Objective-C Initializer for a class.

objective-c,nsstring,initializer
This code is from the Sams Teach Yourself Swift book, Chapter 21. The Song.h file contains the following code: //Song.h #import <Foundation/Foundation.h> @interface Song : NSObject; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *artist; @property (nonatomic, strong) NSNumber *rating; - (instancetype)initWithTitle:(NSString *)title artist:(NSString *)artist rating:(NSNumber *)number; @end To...

NSString string based on CGSIZE

ios,nsstring
I have a long NSString and want to get only the string which gets fit in CGSize. Example: NSString *temp = @"jump jump jump jump jump jump"; CGSize = CGSizeMake(30,30); UIFont *font = [UIFont fontwithName:@"helviticaNueue" fontSize:18]; Please ignore the syntax. From above details can i get what NSString fits the...

isEqualToString not evaluating true

cocoa-touch,nsstring,nsdata
Method: - (void)serverResponse:(NSData *)data { NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", response); NSLog(@"%i", [response isEqualToString:@"1"]); } Log: 2015-03-15 06:26:53.716 appName[687:60b] 1 2015-03-15 06:26:53.718 appName[687:60b] 0 This doesn't seem to make any sense. I'm guessing the problem has something to do with the encoding, but I'm not sure what....

Send NSString as body of post method using NSURLSession

ios,objective-c,nsstring,nsdictionary,nsurlsession
I am trying to post a string to a server using the next example: // 1 NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; // 2 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; // 3 NSDictionary *dictionary = @{@"key1": @"value1"}; NSError...

What does @“//” do in childWithName and when to use it

ios,nsstring,sprite-kit,sknode
I'm working on a SpriteKit project and my SKSpriteNode has a simple name: node.name = @"cat" However, when I try to do [self childWithName:@"cat"], I do not retrieve my object. Through some research I noticed some people mentioning I should be doing [self childWithName:@"//cat"] and that works. I was wondering...

Confused by NSStringDrawingOptions item meaning

ios,nsstring,nsattributedstring,textkit
iOS7 and later, we can use - (void)drawWithRect:(CGRect)rect options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context to calculate the string size, but I'm confused with the comments on NSStringDrawingOptions enum. NSStringDrawingUsesLineFragmentOrigin It means specified origin is the line fragment origin, not the base line origin. But what mean of line fragment origin and...

How to convert NSString to NSDate in IOS?

ios,objective-c,nsstring,nsdate,nsdateformatter
I am building an application where I need to convert The NSString to NSDate. I have googled and found a lot links of SOF mentioned below - http://stackoverflow.com/questions/3917250/converting-nsstring-to-nsdate-and- back-again Convert NSString to NSDate Converting can NSString to NSDate format in objective C I had used the answer given there but...