I have a define:
hashdefine kPingServerToSeeIfInternetIsOn "http://10.0.0.8"
then in code I with to use it:
NSString *theURL = [NSString stringWithFormat:#"%#", kPingServerToSeeIfInternetIsOn];
I get an exception.
What's the best way to define the const for the application and use it in a NSString init?
You've #defined it as a C string.
If you want it as an Objective-C String, you need
#define kPingServerToSeeIfInternetIsOn #"http://10.0.0.8"
Create a header file, e.g. MyAppConstants.h. Add the following:
extern NSString * const kPingServerToSeeIfInternetIsOn;
In the definition, e.g. MyAppConstants.m, add:
NSString * const kPingServerToSeeIfInternetIsOn = #"http://10.0.0.8";
In your class implementation, add:
#import "MyAppConstants.h"
You can use the constant as you have done already.
Related
I am having a few global variables declared in an NSObject class.
NSString *const SAT_NAME=#"http://you.com";
NSString *const DOMAIN= [NSString stringWithFormat:#"%#name/",SAT_NAME,nil];
I want to append the DOMAIN as shown (http://you.com/name/), but it does not work. How can i fix this ?
NSString *const SAT_NAME=#"http://you.com";
NSString *const DOMAIN= [NSString stringWithFormat:#"%#name/",SAT_NAME,nil];
Look at the format string. It starts with %#. The %# is replaced with "http://you.com". Now if you use copy and paste, you see that the result is
http://you.comname/
I don't quite see what you think the nil is good for. There is no formatting for it, so it is just ignored.
I am very much new to iOS so i don't have an idea.I am developing an application in which i am fetaching data from the server.So i have some of the url from which i will featch the data.I want to decalre all the url in a seperate file & use them in another file.I have created AppConst.h & AppConst.m.
AppConst.h
#import <Foundation/Foundation.h>
#interface AppConstant : NSObject
extern NSString const *BASE_URL;
extern NSString const *LOGIN;
extern NSString const *CREATE_ACCOUNT;
extern NSString const *UPDATE_PROFILE;
extern NSString const *ADD_BUSINESS_CARD;
extern NSString const *ADD_NONBUSINESS_CARD;
extern NSString const *ADD_EVENT_CARD;
#end
AppConst.m
#import "AppConstant.h"
#implementation AppConstant
NSString const *BASE_URL=#"http://localhost:8080/app/v1";
NSString const *LOGIN=#"/login";
NSString const *UPDATE_PROFILE=#"/create_account";
NSString const *ADD_BUSINESS_CARD=#"/addBusinessCard";
NSString const *ADD_NONBUSINESS_CARD=#"addNonBusinessCard";
NSString const *ADD_EVENT_CARD=#"addEventCard";
#end
But i am not able to append the string of BASE_URL with LOGIN url.
I get the error as below
sending 'const_NSString *__strong' to parameter of type "NSString discards qualifiers.
You should declare your constant string as follows:
NSString * const kSomeConstantString = #""; // constant pointer
The former is a constant pointer to an NSString object, while the later is a pointer to a constant NSString object.
Using a NSString * const prevents you from reassigning kSomeConstantString to point to a different NSString object.
The method isEqualToString: expects an argument of type NSString *. If you pass a pointer to a constant string (const NSString *), you are passing something different than it expects.
Besides, NSString objects are already immutable, so making them const NSString is meaningless.
Or else you can declare constant like this also
#define kSomeConstantString #""
better idea to make constants file is to create header file and add all the static constants like below:
// Host Url
#define BASE_URL #"http://localhost:8080/app/v1"
// login Url
#define LOGIN #"/login"
and than add the constants file.h in the parent view controller and than you can use everywhere in the app. and even if you want to append string than you can use the below code the create url from your code:
NSString *loginURL = [NSString stringWithFormat:#"%#%#", BASE_URL, LOGIN];
Thanks, May be help you to learn new things.
I want to use Static Var to save a NSString.
So I define a Static Var in a .h file like this:
#ifndef GlobalParameters_h
#define GlobalParameters_h
//access token
static NSString *applicationToken;
#endif
In class A, I change the static var like this:
#import "ClassA.h"
#import "GlobalParameters.h"
extern NSString *applicationToken;
#implementation ClassA
+ (void)parseResponse:(NSString *)response
{
NSDictionary *responseDic = [response objectFromJSONString];
NSString *token = [responseDic objectForKey:#"token"];
applicationToken = [token copy];
NSLog(#"%#",applicationToken);
}
When the debugger run to
applicationToken = [token copy];
I found the "applicationToken" is nil,but the next sentence
NSLog(#"%#",applicationToken);
can output the right value in console! And in ClassB , the "applicationToken" is nil too.
I don't know why the static var is nil. I think the compiler will find the definition of "applicationToken" in GlobalParameters.h.But why I can't modify the static value?
Thanks for your help:)
static global variable mean that it's own for every object-file it's used. So there is willbe own applicationToken for ClassA, ClassB.
To create global variable for all object-files you need this:
In GlobalParameters.h:
#ifndef GlobalParameters_h
#define GlobalParameters_h
//access token
extern NSString *applicationToken;
#endif
In GlobalRarameters.m:
#import "GlobalParameters.h"
NSString *applicationToken;
P.S. I hope you use ARC, because if not, then applicationToken = [token copy]; will cause memory leaks.
Hey Its working fine , I am checking like this
Once check the are you getting "responseDic" (or) not , Check the
The dictionary have token key
static NSString *applicationToken;
applicationToken = #"srinivas";
NSLog(#"%#",applicationToken);
NSDictionary *responseDic = [NSDictionary dictionaryWithObject:#"static" forKey:#"token"];
NSString *token = [responseDic objectForKey:#"token"];
applicationToken = [token copy];
NSLog(#"%#",applicationToken);
[AppDelegate parseResponse:responseDic];
I'm trying to concatenate 2 strings assigning the result to a new string.
Normally I would do this way:
NSString * s = [NSString stringWithFormat: #"%#%#", str1, str2];
Now I wish s to be static
static NSString * s = [NSString stringWithFormat: #"%#%#", str1, str2];
but compiler kick me with "Initializer element is not a compile-time..."
Is there any way to do this? I Googled a bit with no results and also I have not found answers on StackOverflow asking the question.
And what about using a short form like (in PHP)
$s = $str1.$str2;
Any help will be appreciated.
EDIT: What i want to achieve is to have a config file like this (in PHP code)
define ("BASE_URL", "mysite.com/");
define ("SERVICE_URL1", BASE_URL."myservice1.php?param1=value1");
define ("SERVICE_URL2", BASE_URL."myservice2.php?param2=value2");
I prefer to have all configurations strings in 1 file and i found usefull static strings in objective c. Just want to put 2 usefull thing together :)
EDIT2: There's no metter if i obtain this with defines, but the NSString way is preferred and i use static just beacause const make me some compilation problems i haven't solved yet
Use this code for creating static s:
static NSString * s = nil;
if (!s)
s = [NSString stringWithFormat: #"%#%#", str1, str2];
Also for concatenating two string you case use such code: NSString *s = [str1 stringByAppendingString: str2];
UPDATED:
You can concat static string by putting them one by one.
Example:
#define STR1 #"First part" #" Second part"
#define STR2 #"Third part " STR1
NSLog(#"%#", STR2);
This cole will print Third part First part Second part
I think below lines may help:
NSString *str1 = #"String1";
NSString *str2 = #"String2";
NSString *combinedStr = [str1 stringByAppendingString:str2];
If you can use a define, it is pretty simple:
#define A #"a"
#define B #"b"
…
static NSString *ab = A B; // or: #"A" #"B"
You can always concatenate string literals with a single space.
But something very important has to happen to use defines. What's wrong with computing it non-static or compute it once?
BTW: You should use dispatch_once() and not if. For the reasons you can search "dispatch_once" on SO.
If you don't mind compiling Objective-C++ code, you could simply change the extension from .m to .mm, by default XCode compiles according to file type, and this is valid in Objective-C++
Solved this way:
#define kBaseURL #"mysite.com/"
static NSString *kServiceUrl1 = kBaseURL #"myservice1.php?param1=value1";
static NSString *kServiceUrl2 = kBaseURL #"myservice2.php?param2=value2";
thanks all.
now the question is
wich one i have to accept as right answer? I mean, mine is the solution, but I would never have got there without your help guys
Okey!
So how can I centralizing the way I set my icons in a larger scale project.
Insted of setting icons with [UIImage ImageNamed: #"iconNamed"]; everywhere and having to look into all the places in your project to change the string whenever an icon is being changed
and insted of having a long list of method implementations returning a string.
The end result should be like:
Alternatively just have constants defined like Apple does for global keys...
In the .h file:
extern NSString *const kIconMenuSmallWht;
extern NSString *const kIconMenuBigWht;
extern NSString *const kIconShoppingSmall;
extern NSString *const kIconShoppingBig;
extern NSString *const kIconSleepingSmall;
extern NSString *const kIconSleepingBig;
In the .m file:
NSString *const kIconMenuSmallWht = #"ag_icons_btn_menu_wht";
NSString *const kIconMenuBigWht = #"c";
NSString *const kIconShoppingSmall = #"ag_icons_idx_ico_shopping_wht";
NSString *const kIconShoppingBig = #"ag_icons_idx_ico_shopping_wht";
NSString *const kIconSleepingSmall = #"ag_icons_idx_ico_shopping_wht_120";
NSString *const kIconSleepingBig = #"ag_icons_idx_ico_hotel_wht_120";
These are constants... global variables are not always bad!
(and many feel singletons are just globals anyway and are just as evil)
This will also give autocomplete in Xcode and have a single place to go for updates/changes but is simpler and has no method calls or objects to create so better performance (albeit likely infinitesimally better performance).
So first you create a .h file like #interface MyIcons : NSObject
and you kick off your singleton implementation with:
+(MyIcons *)sharedIcons ;
followed by:
typedef enum {
IconMenuSmallWht,
IconMenuBigWht,
IconShoppingSmall,
IconShoppingBig,
IconSleepingSmall,
IconSleepingBig,
} iconType;
- (NSString*) iconToString:(iconType) chooseIcon;
in the .m file you finish up your singleton implementation first:
+(MyIcons *)sharedIcons {
static dispatch_once_t once;
static MyIcons *sharedIcons = nil;
dispatch_once(&once, ^{
sharedIcons = [[self alloc] init];
});
return sharedIcons;
}
and you end with doing:
- (NSString*) iconToString:(iconType) chooseIcon {
NSString *result = nil;
switch(chooseIcon) {
case IconMenuSmallWht:
result = #"ag_icons_btn_menu_wht";
break;
case IconMenuBigWht:
result = #"c";
break;
case IconShoppingSmall:
result = #"ag_icons_idx_ico_shopping_wht";
break;
case IconShoppingBig:
result = #"ag_icons_idx_ico_shopping_wht_120";
break;
case IconSleepingSmall:
result = #"ag_icons_idx_ico_hotel_wht";
break;
case IconSleepingBig:
result = #"ag_icons_idx_ico_hotel_wht_120";
break;
return result;
}
Thats it. It just add icons to the enum and to this switch/case.
and wherevever you want to implement your icons you just #import MyIcons.h
add [MyIcons SharedIcons]iconToString: and voila you get your list of choosing.
Hope you enjoy this way of doing it. I know I will! (-:-)