Function with no arguments works just fine, with arguments - crashes - xcode

it works with no problems:
h file:
- (BOOL) trytoGETURL;
m file
- (BOOL) trytoGETURL {
/ some code here ...
if ([response statusCode] == 200)
return YES;
else
return NO;
}
- (IBAction)ButtonTouchUp:(id)sender {
NSLog(#"button clicked");
if ( [self trytoGETURL]) {
NSLog(#"ok");
} else NSLog(#"problem");
but this crashes:
h file
- (BOOL) trytoGETURL:(NSString *) baseurl Redvalue:(int)red
GreenValue:(int)green BlueValue: (int) blue;
m file
- (BOOL) trytoGETURL:(NSString *) baseurl Redvalue:(int)red
GreenValue:(int)green BlueValue: (int) blue {
if ([response statusCode] == 200)
return YES;
else
return NO;
}
- (IBAction)ButtonTouchUp:(id)sender {
NSLog(#"button clicked");
if ( [self trytoGETURL:#"sd" Redvalue:100 Greenvalue:100 Bluevalue:100]) {
NSLog(#"est takaya stranica");
} else NSLog(#"net takoi stranica");
Xcode also writes: instance method not found!??
and by the way it doesn't help me with when I'm starting to write like usual, why is it so?

Check your capitalization:
trytoGETURL:Redvalue:Greenvalue:Bluevalue:
is most certainly not the same as:
trytoGETURL:RedValue:GreenValue:BlueValue:

it was just a problem with suntax.
trytoGETURL:(NSString *) baseurl - is wrong,
trytoGETURL:(NSString *)baseurl is right. - no space needed.

Related

How to use the orientation with out using auto layout in Xcode?

I am just start to learning about Xcode. i need to create an app in which it should be able to view correct manner in all the view (Landscape, Portrait). Condition here is should not using the auto layout.
Is any other way to use the story board for the same solution?
Other way is you have to programmatically handle the frame and other things in the following delegate functions. I have shown code for landscape mode only
//THis only work for ios<6.0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if(interfaceOrientation== UIInterfaceOrientationPortrait || interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
return NO;
}
else
{
return YES;
}
}
//THis work for ios >=6.0
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
UIInterfaceOrientation interfaceOrientation=[[UIApplication sharedApplication] statusBarOrientation];
if(interfaceOrientation== UIInterfaceOrientationPortrait || interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
return NO;
}
else
{
//landscape mode code
return ( UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
UIInterfaceOrientation orientation=self.interfaceOrientation;
if(orientation== UIInterfaceOrientationPortrait || orientation==UIInterfaceOrientationPortraitUpsideDown )
{
//portrait mode code
}
else
{
//landscape mode code
}
}

Every time on scanning bluetooth devices gives CBCentralManagerStateUnknown?

First time I am using coreBluetooth.
Here is my implementation is there any thing wrong in it.
#synthesize CM,activePeripheral;
- (id)init
{
if ((self = [super init]))
{
CM = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (int) scanForPeripherals
{
if (self.CM.state != CBCentralManagerStatePoweredOn)
{
NSLog(#"CoreBluetooth is %s",[self centralManagerStateToString:self.CM.state]);
return -1;
}
[self.CM scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:#"180D"]] options:#{CBCentralManagerScanOptionAllowDuplicatesKey: #YES}];
return 0;
}
- (const char *) centralManagerStateToString: (int)state
{
switch(state)
{
case CBCentralManagerStateUnknown:
return "State unknown (CBCentralManagerStateUnknown)";
case CBCentralManagerStateResetting:
return "State resetting (CBCentralManagerStateUnknown)";
case CBCentralManagerStateUnsupported:
return "State BLE unsupported (CBCentralManagerStateResetting)";
case CBCentralManagerStateUnauthorized:
return "State unauthorized (CBCentralManagerStateUnauthorized)";
case CBCentralManagerStatePoweredOff:
return "State BLE powered off (CBCentralManagerStatePoweredOff)";
case CBCentralManagerStatePoweredOn:
return "State powered up and ready (CBCentralManagerStatePoweredOn)";
default:
return "State unknown";
}
return "Unknown state";
}
- (void) connectPeripheral:(CBPeripheral *)peripheral {
printf("Connecting to peripheral with UUID : %s\r\n",[self UUIDToString:peripheral.UUID]);
self.activePeripheral = peripheral;
self.activePeripheral.delegate = self;
[self.CM connectPeripheral:self.activePeripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
}
-(const char *) UUIDToString:(CFUUIDRef)UUID
{
if (!UUID)
return "NULL";
CFStringRef s = CFUUIDCreateString(NULL, UUID);
return CFStringGetCStringPtr(s, 0);
}
#pragma mark -Central manager delegate method
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSLog(#"hits it");
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
isOn=YES;
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(#"Received periferal :%#",peripheral);
NSLog(#"Ad data :%#",advertisementData);
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(#"Connected peripheral %#",peripheral);
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(#"Error occured :%#",[error localizedDescription]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanDevices:(id)sender {
if (isOn) {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self scanForPeripherals];
}
}
Every time it gives log
CoreBluetooth is State unknown (CBCentralManagerStateUnknown)
update to question
After suggestion given by #Michael Dautermann , I come to know that my centralManagerDidUpdateState delegate method is not hitting.I dunno why this is happening.If anybody finds the reason please notify me.
Thanks you.
CoreBluetooth is simply in the process of starting up.
You need this delegate method to hit first:
- (void) centralManagerDidUpdateState: (CBCentralManager *) central;
And once it does, then you can start scanning for peripherals.
After few days, I checked out the initialization of CentralManager and I come to know that init method on firstViewController never called.I checked out by printing log in init method.
- (id)init
{
NSLog(#"hello init");
if ((self = [super init]))
{
CM = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
}
return self;
}
- (void)viewDidLoad
{ CM = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
isOn=NO;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
So , I initialize the central manager in viewDidLoad and now it is initialized and centralManagerDidUpdateState finally called.Now printing CBCentralManagerStateUnsupported and that's not the issue because iPhone 4 doesn't support it.Thanks to michael help me a lot.
Where do you call scanDevices? I think you're calling it too early. You should call it inside centralManagerDidUpdateState.
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSLog(#"hits it");
if (central.state != CBCentralManagerStatePoweredOn) {
[self scanDevices]:
}
isOn=YES;
}

randomly displaying sprite image

Hi currently my game is loading fl_gfood.png or fl_bfood.png from the fl_food.plist. That works fine but now I have 17 bad food items .png and 17 good food items .png. My question is how do I randomly display one of the 17 items from each group? Can I just do a wildcard for the sprite png file name? See code comment below. Also a suggestion was made that I could possibly load the .plist file names into an array and randomly pick a name, how would that be done.
#implementation Food
+ (void)loadAssets {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[[FLSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:[AssetHelper getDeviceSpecificFileNameFor:#"fl_food.plist"]];
});
}
- (id)init {
self = [super init];
if (self) {
self.size = CGSizeMake(16 * __HIGHRES_SCALE, 16 * __HIGHRES_SCALE);
self.offset = CGPointMake(8 * __HIGHRES_SCALE, 8 * __HIGHRES_SCALE);
self.removeAfterCollision = YES;
self.collideable = NO;
self.score = 10;
}
return self;
}
- (FLSprite *)sprite {
if(_sprite == nil) {
if(self.score < 10) {
_sprite = [FLSprite spriteWithSpriteFrameName:#"fl_gfood.png"]; // fl_gfood_*.png ... Can I do something like this?
} else {
_sprite = [FLSprite spriteWithSpriteFrameName:#"fl_bfood.png"];
}
}
return _sprite;
}
I would use arc4random() and stringByAppendingString
- (FLSprite *)sprite {
if(_sprite == nil) {
NSString *disFood;
disFood = (self.score < 10) ? #"fl_gfood" : #"fl_bfood";
//random # between 1 - 10
int randNum = (arc4random() % 10)+1;
NSString *formattedName = [NSString stringWithFormat:#"_%i.png",randNum];
disFood = [disFood stringByAppendingString:formattedName];
_sprite = [FLSprite spriteWithSpriteFrameName:disFood];
NSLog(disFood);//Logging disFood String;
}
return _sprite;
}

How to check that current space is Dashboard?

Sample code is
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:#selector(activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
Then
- (void) activeSpaceDidChange:(NSNotification *)aNotification {
// code to check if current workspace is dashboard?
}
I want to check whether the current space is dashboard or not? Any idea?
The first think i have tried is get to the current space id according to this answer: Detecting when a space changes in Spaces in Mac OS X . The problem here is that the key kCGWindowWorkspace is deprecated in OSX 10.8. So there is no direct way to get this information.
In my solution now i check for different windows or owners which are only one the dashboard space or on all other spaces:
The user is on the dashboard if there is one window which kCGWindowName ends with .wdgt/
The user is not on the dashboard if there is one window with kCGWindowName == System Status Item Clone, kCGWindowOwnerName == SystemUIServer | Finder
So why i'm not just using the .wdgt/ check? -- Because if there is now widget on the dashboard this not working
So why i'm using more than one window check? -. Because i'm not jet sure which window is always on all spaces. At least System Status Item Clone and Finder are not always there.
Here my implementation is add this function as category to NSWorkspace
- (BOOL) userIsOnDashboardSpace {
NSArray* windowsInSpace = (__bridge NSArray *) CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
NSUInteger indexOfWidget = [windowsInSpace indexOfObjectPassingTest:^BOOL(NSDictionary* obj, NSUInteger idx, BOOL *stop) {
if ([obj objectForKey:(id)kCGWindowName]) {
NSString *name = (NSString *)[obj objectForKey:(id)kCGWindowName];
if ([name isEqualToString:#"System Status Item Clone"]) {
*stop = true;
return false;
}
if ([name hasSuffix:#".wdgt/"]) {
*stop = true;
return true;
}
}
if ([obj objectForKey:(id)kCGWindowOwnerName]) {
NSString *name = (NSString *)[obj objectForKey:(id)kCGWindowOwnerName];
if ([name isEqualToString:#"SystemUIServer"]) {
*stop = true;
return false;
}
if ([name isEqualToString:#"Finder"]) {
*stop = true;
return false;
}
}
return false;
}];
return indexOfWidget != NSNotFound;
}

Check if last characters of an NSString are numbers

Is it possible to see of a string ends with a number which length is not known?
"String 1" -> 1
"String 4356" -> 4356
"String" -> nil
If so, how can I determine that number?
To test that a string ends with numbers, you can use an NSPredicate, such as:
NSPredicate endsNumerically = [NSPredicate predicateWithFormat:#"SELF matches %#", #"\\d+$"];
[endsNumerically evaluateWithObject:string]; // returns TRUE if predicate succeeds
NSScanner is sometimes useful for extracting things from strings, but it doesn't scan backward. You could define a Gnirts (reverse string) class and use that with an NSScanner, but that's probably more hassle than it's worth.
NSString's rangeOfCharacterFromSet:options:, which I had hope to use, only looks for a single character (it's like strchr and strrchr, if you're familiar with C), but we can roll our own that returns a contiguous range of characters from a set (a little like strspn) as a category on NSString. While we're at it, let's include methods that return substrings rather than ranges.
RangeOfCharacters.h:
#interface NSString (RangeOfCharacters)
/* note "Characters" is plural in the methods. It has poor readability, hard to
* distinguish from the rangeOfCharacterFromSet: methods, but it's standard Apple
* convention.
*/
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet;
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask;
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range;
// like the above, but return a string rather than a range
-(NSString*)substringFromSet:(NSCharacterSet*)aSet;
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask;
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range;
#end
RangeOfCharacters.m:
#implementation NSString (RangeOfCharacters)
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet {
return [self rangeOfCharactersFromSet:aSet options:0];
}
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask {
NSRange range = {0,[self length]};
return [self rangeOfCharactersFromSet:aSet options:mask range:range];
}
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range {
NSInteger start, curr, end, step=1;
if (mask & NSBackwardsSearch) {
step = -1;
start = range.location + range.length - 1;
end = range.location-1;
} else {
start = range.location;
end = start + range.length;
}
if (!(mask & NSAnchoredSearch)) {
// find first character in set
for (;start != end; start += step) {
if ([aSet characterIsMember:[self characterAtIndex:start]]) {
#ifdef NOGOTO
break;
#else
// Yeah, a goto. If you don't like them, define NOGOTO.
// Method will work the same, it will just make unneeded
// test whether character at start is in aSet
goto FoundMember;
#endif
}
}
#ifndef NOGOTO
goto NoSuchMember;
#endif
}
if (![aSet characterIsMember:[self characterAtIndex:start]]) {
NoSuchMember:
// no characters found within given range
range.location = NSNotFound;
range.length = 0;
return range;
}
FoundMember:
for (curr = start; curr != end; curr += step) {
if (![aSet characterIsMember:[self characterAtIndex:curr]]) {
break;
}
}
if (curr < start) {
// search was backwards
range.location = curr+1;
range.length = start - curr;
} else {
range.location = start;
range.length = curr - start;
}
return range;
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet {
return [self substringFromSet:aSet options:0];
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask {
NSRange range = {0,[self length]};
return [self substringFromSet:aSet options:mask range:range];
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range {
NSRange range = [self rangeOfCharactersFromSet:aSet options:mask range:range];
if (NSNotFound == range.location) {
return nil;
}
return [self substringWithRange:range];
}
#end
To use the new category to check that a string ends with digits or to extract the number:
NSString* number = [string substringFromSet:[NSCharacterSet decimalDigitCharacterSet]
options:NSBackwardsSearch|NSAnchoredSearch];
if (number != nil) {
return [number intValue];
} else {
// string doesn't end with a number.
}
Lastly, you can use a third party regular expression library, such as RegexKit or RegexkitLite.
I couldn't get the NSPredicate code above to work correctly, though it looks like it should. Instead I accomplished the same thing with
if ([string rangeOfString:#"\\d+$" options:NSRegularExpressionSearch].location != NSNotFound) {
// string ends with a number
}
Hat-tip to this answer.

Resources