This seems like a relatively easy question but I am getting errors. I am working on an iBeacon project which will display different messages to the user depending on which iBeacon they are closest to. I already set up major and minor values from the transmitter and then tried calling them in a different class but I get errors saying "Expected Identifier"
self.majorLabel.text = [NSString stringWithFormat:#"%#", beacon.major];
self.minorLabel.text = [NSString stringWithFormat:#"%#", beacon.minor];
self.accuracyLabel.text = [NSString stringWithFormat:#"%f", beacon.accuracy];
if (([beacon.minor] == 1) && ([beacon.major] == 2) && (beacon.proximity == CLProximityFar)) {
self.distanceLabel.text = #"Good Bye";
self.distanceLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#""]];
Is there something i am doing wrong here??
Which line is giving an error, and what is the exact text of the error? I'm guessing it's the if statement, since that's the only line of your code that includes beacon minor and major values.
What is the variable "beacon"? Is it of type CLBeacon? I would assume so.
The major and minor value properties of a CLBeacon object (and also of a CLBeaconRegion object) are NSNumbers, not integers. Thus your if statement should read
if (([[beacon.minor] integerValue] == 1) &&
([[beacon.major] integerValue] == 2) &&
(beacon.proximity == CLProximityFar))
{
}
Based on your error message: Expected identifier it appears you are mixing the property dot (.) and message syntax.
Change your code:
if (([beacon.minor] == 1) && ([beacon.major] == 2) && (beacon.proximity == CLProximityFar)) {
...
}
to either property (.) syntax (removing the [] brackets):
if ((beacon.minor == 1) && (beacon.major == 2) && (beacon.proximity == CLProximityFar)) {
...
}
or method syntax (removing the .):
if (([beacon minor] == 1) && ([beacon major] == 2) && (beacon.proximity == CLProximityFar)) {
...
}
Related
I want to find total number of close shape.
In image, there are 6 no of close polygons .
I have tried following method
for (NSInteger i = 0; i < [arrLinesInfo count]; i++) {
NSDictionary *dictLineInfo = [arrLinesInfo objectAtIndex:i];
startPoint = CGPointMake([[dictLineInfo valueForKey:#"line_start_point_x"] doubleValue], [[dictLineInfo valueForKey:#"line_start_point_y"] doubleValue]);
endPoint = CGPointMake([[dictLineInfo valueForKey:#"line_end_point_x"] doubleValue], [[dictLineInfo valueForKey:#"line_end_point_y"] doubleValue]);
[self isCircularRoute:startPoint withEndPoint:endPoint];
}
-(void) isCircularRoute:(CGPoint) lineStartPoint withEndPoint:(CGPoint) lineEndPoint
{
NSPredicate *pre= [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"
(self.line_end_point_x == '%f' && self.line_end_point_y == '%f') OR
(self.line_start_point_x == '%f' && self.line_start_point_y == '%f') OR
(self.line_end_point_x == '%f' && self.line_end_point_y == '%f') OR
(self.line_start_point_x == '%f' && self.line_start_point_y == '%f')", lineStartPoint.x,
lineStartPoint.y,
lineStartPoint.x,
lineStartPoint.y,
lineEndPoint.x,
lineEndPoint.y,
lineEndPoint.x,
lineEndPoint.y]];
NSMutableArray *arrSamePointRef = [[arrLinesInfo filteredArrayUsingPredicate:pre] mutableCopy];
arrSamePointRef = [[arrSamePointRef filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:#"
(self.line_start_point_x != '%f' && self.line_start_point_y != '%f') &&
(self.line_end_point_x != '%f' && self.line_end_point_y != '%f')", lineStartPoint.x
, lineStartPoint.y
, lineEndPoint.x
, lineEndPoint.y]]] mutableCopy];//[arrSamePointRef removeObject:dictLineInfo];
if(arrSamePointRef.count > 2){
totalPolygon = totalPolygon + 1;
}
NSLog(#"totalPolygon : ===== %tu", totalPolygon);
for (NSDictionary *dictSingleLine in arrSamePointRef) {
CGPoint newStartPoint = CGPointMake([[dictSingleLine valueForKey:#"line_start_point_x"] doubleValue], [[dictSingleLine valueForKey:#"line_start_point_y"] doubleValue]);
CGPoint newEndPoint = CGPointMake([[dictSingleLine valueForKey:#"line_end_point_x"] doubleValue], [[dictSingleLine valueForKey:#"line_end_point_y"] doubleValue]);
[self isCircularRoute:newStartPoint withEndPoint:newEndPoint];
}
}
This is go in infinite loop.
I have all start point and end point object in array.
array object like below
[
{
"point_start_lbl" : "a",
"point_end_lbl" : "b",
"line_start_point_x" : 200,
"line_start_point_y" : 10,
"line_end_point_x" : 100,
"line_end_point_y" : 10,
}, ...
]
Please help me.
Thanks in advance.
You definitely have a closed polygon if you have an ordered list of edges such that each edge ends on the vertex that the next starts on and no edge is repeated within the list.
I'm unclear about your data structure but I might therefore:
Define an object, Edge that identifies two vertices.
For each vertex, create an array containing every single edge that touches that vertex.
Then, something like, in Swift-ish pseudocode:
var successfulPaths: [Edge] = []
for edge in edges
{
let usedEdges = [edge]
attemptTraversalFrom(edge.vertex1, edge.vertex2, usedEdges, successfulPaths)
attemptTraversalFrom(edge.vertex2, edge.vertex1, usedEdges, successfulPaths)
}
print("There were \(successfulPaths.count) successful paths")
[...]
func attemptTraversalFrom(startingVertex, endingVertex, usedEdges, successfulPaths) {
let vertexEdges = endingVertex.edges
for edge in (edges not in usedEdges) {
let newEndingVertex =
(edge.vertex1 == endingVertex) ? edge.vertex2 : edge.vertex1
if newEndingVertex == startingVertex {
successfulPaths.add(usedEdges)
return
} else {
let newUsedEdges = userEdges.addItem(edge)
attemptTraversalFrom(startingVertex, newEndingVertex, newUsedEdges, successfulPaths)
}
}
// Note: will automatically fall through to here and return
// without adding anything to `successfulPaths` if there are
// no further traversable edges
}
Extemporaneous, etc. A bit like the recursive part of Dijkstra's pathfinding algorithm, except that potential paths are accumulated rather than shorter paths eliminating longer ones prior to complete evaluation.
I need to check in two of string, if those string contains any particular string or not
NSString *startLocationAddress = #"Any address for start location";
NSString *endLocationAddress = #"Any address for end location";
if ([startLocationAddress rangeOfString:#"Australia"].location == NSNotFound)
{
NSLog(#"string does not contain Australia");
startLocationAddress = [startLocationAddress stringByAppendingString:#",Australia"];
}
else if ([endLocationAddress rangeOfString:#"Australia"].location == NSNotFound)
{
NSLog(#"string does not contain Australia");
endLocationAddress =[endLocationAddress stringByAppendingString:#",Australia"];
}
else {
NSLog(#"string contain Australia");
}
As my both of strings does not contains "Australia". So the first condition will be checked first and if the first condition valid then it exit out of the conditions, if the first condition is not valid then only it check the else if condition. In this way the if else if conditional works.
As my both of strings does not contains "Australia". First if condition is working fine and it append "Australia" to the string but second else if condition is not working
How on earth can an else if block execute when it's corresponding if was executed? Expectation is not logical.
If you want your else if block to also check then separate it from your main if and start a new if condition, not an else if
You better reconstruct it like:
if ([startLocationAddress rangeOfString:#"Australia"].location == NSNotFound)
{
//codes..
}
else
{
NSLog(#"startLocationAddress contain Australia");
}
if ([endLocationAddress rangeOfString:#"Australia"].location == NSNotFound)
{
//codes..
}
else
{
NSLog(#"endLocationAddress contain Australia");
}
and review how if-else if-else statement works.. See: #
Hanky 웃 Panky answer for that, since confusion is very prone to us..
if (ifcondition)
{ .. }
else if (elseifcondition)
{ .. }
else
{ .. }
/*
if `ifcondition` == true, dont expect anything from `else-if` or `else`,
compiler won't care about them anymore. that goes with `else-if` and `else` as well..
*/
In if-else if-else condition if any of one is gets satisfied it will ignore the rest of the condition.
This means if First if gets satisfied, then it will ignore the "else if - else". Hence your second condition is not executing.
You are required to read the basic if else logic of execution.
Here is the example
int x=70;
string Grade;
IF (x > 90) THEN
Grade = "O"
ELSE IF (x > 80) THEN
Grade = "A"
ELSE IF (x > 70) THEN
Grade = "B"
ELSE IF (x > 60) THEN
Grade = "C"
ELSE
Grade = "F"
Here the value for variable Grade will be only one per execution.
I'm attempting to check two input textfields that the user type in to see if they put in either AM or PM (going for non-case sensitive). If they did, post the event otherwise display an alert.
I tried this, it works in some occasions, but when I type in PM and AM in the second it sometimes tells me it's not valid and returning my alert. Any idea where I got the logic wrong?
if(!([self.eventStartTimeSuffix.text isEqualToString:#"AM"] || [self.eventStartTimeSuffix.text isEqualToString:#"PM"]) && !([self.eventEndTimeSuffix.text isEqualToString:#"AM"] || [self.eventEndTimeSuffix.text isEqualToString:#"PM"]))
{
NSLog(#"Invalid Event / Start Time Suffix, AM or PM required");
}
else
{
//post event
}
In trying to test for not AM/PM you are testing for both being invalid, your test is: NOT(StartTimeSuffix is AM/PM) AND NOT(EndTimeSuffix is AM/PM). So first either use OR to join the separate conditions or test them independently so you can present a more specific error.
You are also not ignoring case as you say you wish to, and if the user enters some whitespace it might be worth ignoring that as well. You can do both of these with code such as:
NSSString *startSuffix = [[self.eventStartTimeSuffix.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lowercaseString];
and then comparing startSuffix to #"am" and #"pm", likewise for eventEndTimeSuffix.
BTW You might be even better off if you use the international facilities of OS X and compare for the localised versions of AM & PM - but that is another topic!
Add parentheses to make your grouping clear:
Pseudocode (this is not real code!):
if (
(startText == "AM" || startText == "PM")
&&
(endText == "AM" || endText "PM")
)
{
//Both fields contain either "AM" or PM"
}
Note that if you want case insensitive comparison, you should use
if ([string caseInsensitiveCompare: #"otherString"] == NSOrderedSame)
{
//strings match, ignoring case
}
else
{
//strings don't match
}
You also may as well factor out a method to make it more readable:
- (BOOL)hasValidTimeSuffix:(NSString *)timeText {
return [[timeText lowercaseString] hasSuffix:#"am"] || [[timeText lowercaseString] hasSuffix:#"pm"]
}
and then
if ([self hasValidTimeSuffix:self.eventStartTimeSuffix.text] && [self hasValidTimeSuffix:self.eventEndTimeSuffix.text])
{
//post event
}
else
{
NSLog(#"Invalid Event / Start Time Suffix, AM or PM required");
}
Notice the use of NSString's lowercaseString and hasSuffix: methods. These help a lot.
Why would you bother checking for the input of textfields? Won't it be wiser to use a NSPopUpButton? Check the selected tag 0:AM or 1:PM. It's just an idea, but it screams for a NSPopUpButton. Cheers!
if
([sender selectedTag] == AM)
{
NSLog(#"it's AM");
}
else if([sender selectedTag] == PM)
{
NSLog(#"it's PM");
}
//Sender is one of the two NSPopUpButtons
//I made a Typedef Enum to make it more readable
/*In the .h file:
typedef enum {
AM,
PM
} TimeNotation;
*/
I'm struggling with an if Comparison - I basically want to make two comparisons - both of which need to pass - Firstly a basic if a string variable is equal to 'rec' and secondly if a strings character limit is not equal to zero.
I've tried various combinations - but this is where i'm at at the mo..
ArticleObject *A = [self.articleArray objectAtIndex:indexPath.section];
NSInteger imglength = [A.arImage length];
if([A.arRec isEqual: #"rec"] ) && (imglength !=Nil){
return 195;
}
else return 50;
I get an expected identifier error on the (imglength comparison - as in this screen shot
Can anyone shed any light for me please?
There are several things you should change:
ArticleObject *A = self.articleArray[indexPath.section];
NSInteger imglength = [A.arImage length];
if (imglength && [A.arRec isEqualToString:#"rec"]) {
return 195;
} else {
return 50;
}
Don't use Nil (or nil) with primitive types.
Your parentheses are messed up:
if([A.arec isEqualToString:#"rec"] && (imglengyb !=Nil))
^--------------//here
Maybe a better way would be:
if([A.arec isEqualToString:#"rec"] && [[A.arImage length] != 0])
I was using this in my iPhone app
if (title == nil) {
// do something
}
but it throws some exception, and the console shows that the title is "(null)".
So I'm using this now:
if (title == nil || [title isKindOfClass:[NSNull class]]) {
//do something
}
What is the difference, and what is the best way to determine whether a string is null?
As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.
So a good test might be:
if (title == (id)[NSNull null] || title.length == 0 ) title = #"Something";
Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.
it is just as simple as
if([object length] >0)
{
// do something
}
remember that in objective C if object is null it returns 0 as the value.
This will get you both a null string and a 0 length string.
Refer to the following related articles on this site:
Is if (variable) the same as if (variable != nil) in Objective-C
h
I think your error is related to something else as you shouldn't need to do the extra checking.
Also see this related question: Proper checking of nil sqlite text column
I have found that in order to really do it right you end up having to do something similar to
if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}
Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual and length checks.
Whats with all these "works for me answers" ? We're all coding in the same language and the rules are
Ensure the reference isn't nil
Check and make sure the length of the string isn't 0
That is what will work for all. If a given solution only "works for you", its only because your application flow won't allow for a scenario where the reference may be null or the string length to be 0. The proper way to do this is the method that will handle what you want in all cases.
If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:
static inline BOOL IsEmpty(id object) {
return object == nil
|| ([object respondsToSelector:#selector(length)]
&& [(NSData *) object length] == 0)
|| ([object respondsToSelector:#selector(count)]
&& [(NSArray *) object count] == 0);
}
There are two situations:
It is possible that an object is [NSNull null], or it is impossible.
Your application usually shouldn't use [NSNull null]; you only use it if you want to put a "null" object into an array, or use it as a dictionary value. And then you should know which arrays or dictionaries might contain null values, and which might not.
If you think that an array never contains [NSNull null] values, then don't check for it. If there is an [NSNull null], you might get an exception but that is fine: Objective-C exceptions indicate programming errors. And you have a programming error that needs fixing by changing some code.
If an object could be [NSNull null], then you check for this quite simply by testing
(object == [NSNull null]). Calling isEqual or checking the class of the object is nonsense. There is only one [NSNull null] object, and the plain old C operator checks for it just fine in the most straightforward and most efficient way.
If you check an NSString object that cannot be [NSNull null] (because you know it cannot be [NSNull null] or because you just checked that it is different from [NSNull null], then you need to ask yourself how you want to treat an empty string, that is one with length 0. If you treat it is a null string like nil, then test (object.length == 0). object.length will return 0 if object == nil, so this test covers nil objects and strings with length 0. If you treat a string of length 0 different from a nil string, just check if object == nil.
Finally, if you want to add a string to an array or a dictionary, and the string could be nil, you have the choice of not adding it, replacing it with #"", or replacing it with [NSNull null]. Replacing it with #"" means you lose the ability to distinguish between "no string" and "string of length 0". Replacing it with [NSNull null] means you have to write code when you access the array or dictionary that checks for [NSNull null] objects.
You just check for nil
if(data[#"Bonds"]==nil){
NSLog(#"it is nil");
}
or
if ([data[#"Bonds"] isKindOfClass:[NSNull class]]) {
NSLog(#"it is null");
}
MACRO Solution (2020)
Here is the macro that I use for safe string instead of getting "(null)" string on a UILabel for example:
#define SafeString(STRING) ([STRING length] == 0 ? #"" : STRING)
let say you have an member class and name property, and name is nil:
NSLog(#"%#", member.name); // prints (null) on UILabel
with macro:
NSLog(#"%#", SafeString(member.name)); // prints empty string on UILabel
nice and clean 😊
Extension Solution (2020)
If you prefer checking nil Null and empty string in your project you can use my extension line below:
NSString+Extension.h
///
/// Checks if giving String is an empty string or a nil object or a Null.
/// #param string string value to check.
///
+ (BOOL)isNullOrEmpty:(NSString*)string;
NSString+Extension.m
+ (BOOL)isNullOrEmpty:(NSString*)string {
if (string) { // is not Nil
NSRange range = [string rangeOfString:string];
BOOL isEmpty = (range.length <= 0 || [string isEqualToString:#" "]);
BOOL isNull = string == (id)[NSNull null];
return (isNull || isEmpty);
}
return YES;
}
Example Usage
if (![NSString isNullOrEmpty:someTitle]) {
// You can safely use on a Label or even add in an Array for example. Remember: Arrays don't like the nil values!
}
if(textfield.text.length == 0){
//do your desired work
}
Try this for check null
if (text == nil)
#interface NSString (StringFunctions)
- (BOOL) hasCharacters;
#end
#implementation NSString (StringFunctions)
- (BOOL) hasCharacters {
if(self == (id)[NSNull null]) {
return NO;
}else {
if([self length] == 0) {
return NO;
}
}
return YES;
}
#end
NSString *strOne = nil;
if([strOne hasCharacters]) {
NSLog(#"%#",strOne);
}else {
NSLog(#"String is Empty");
}
This would work with the following cases, NSString *strOne = #"" OR NSString *strOne = #"StackOverflow" OR NSString *strOne = [NSNull null] OR NSString *strOne.
If that kind of thing does not already exist, you can make an NSString category:
#interface NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty;
#end
#implementation NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty {
return self == nil || [#"" isEqualToString:self];
}
#end
What works for me is if ( !myobject )
Complete checking of a string for null conditions can be a s follows :<\br>
if(mystring)
{
if([mystring isEqualToString:#""])
{
mystring=#"some string";
}
}
else
{
//statements
}
I only check null string with
if ([myString isEqual:[NSNull null]])
if ([linkedStr isEqual:(id)[NSNull null]])
{
_linkedinLbl.text=#"No";
}else{
_linkedinLbl.text=#"Yes";
}
if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:#"<null>"] || [strpass isEqualToString:#"(null)"] || strpass.length==0 || [strpass isEqualToString:#""])
{
//string is blank
}
For string:
+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;
}
Refer the picture below:
For string:
+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;}