How do a make a kMyCustomName = 1 and kMyOtherCustomName = 2 global in my code? [duplicate] - iphone

This question already has answers here:
Constants in Objective-C
(14 answers)
Closed 9 years ago.
I have the following function:
+ (int)isCorrectOnServer:(int)num {
// some code performs here...
if (this)
{
result = 2;
}
else if (this2)
{
result = 1;
}
else
{
result = 0;
}
return result; }
I want it to return like this instead:
+ (int)isCorrectOnServer:(int)num {
// some code performs here...
if (this)
{
result = kOnServer;
}
else if (this2)
{
result = kWrongType;
}
else
{
result = kNotOnServer;
}
return result; }
So anywhere in my code I could just call:
if ([Helper isCorrectOnServer:276872] == kOnServer)
to make my code cleaner and not show 0, 1, or 2 as the result. What is the best way to go about doing this?

When in doubt, see what Apple do. Look in any header file in UIKit and you will see enumeration being used for any kind of value with a finite amount of options.
Just put this in the header file:
typedef enum {
MYCustomTypeOne,
MYCustomTypeTwo,
MyCustomTypeEtcetera
} MYCustomType;
Using proper enumerations over defines allow you to do define a method like this:
+(BOOL)isCustomTypeCorrectOnServer:(MYCustomType)type;
Then the argument can be auto completed for you by Xcode. And the compiler can make much better assumptions if you use the value in a switch case for example.

add the contants to the prefix header file of your project, usually named prefix.pch
Or, an even more clean solution, would be to create a contants file, like contants.h and include this file in your prefix header file.
Prefix.pch
#include Contants.h
Contants.h
#define kMyCustomName 1
#define kMyOtherCustomName 2

#define kMyCustomName 1
#define kMyOtherCustomName 2
Within the scope that they will be used, as Felipe Sabino said to make them truly global they should be in the prefix header.

Related

How to select symbols onWorkspaceSymbol

I am developing an extension for visual studio code using language server protocol, and I am including the support for "Go to symbol in workspace". My problem is that I don't know how to select the matches...
Actually I use this function I wrote:
function IsInside(word1, word2)
{
var ret = "";
var i1 = 0;
var lenMatch =0, maxLenMatch = 0, minLenMatch = word1.length;
for(var i2=0;i2<word2.length;i2++)
{
if(word1[i1]==word2[i2])
{
lenMatch++;
if(lenMatch>maxLenMatch) maxLenMatch = lenMatch;
ret+=word1[i1];
i1++;
if(i1==word1.length)
{
if(lenMatch<minLenMatch) minLenMatch = lenMatch;
// Trying to filter like VSCode does.
return maxLenMatch>=word1.length/2 && minLenMatch>=2? ret : undefined;
}
} else
{
ret+="Z";
if(lenMatch>0 && lenMatch<minLenMatch)
minLenMatch = lenMatch;
lenMatch=0;
}
}
return undefined;
}
That return the sortText if the word1 is inside the word2, undefined otherwise. My problem are cases like this:
My algorithm see that 'aller' is inside CallServer, but the interface does not mark it like expected.
There is a library or something that I must use for this? the code of VSCode is big and complex and I don't know where start looking for this information...
VSCode's API docs for provideWorkspaceSymbols() provide the following guidance (which I don't think your example violates):
The query-parameter should be interpreted in a relaxed way as the editor will apply its own highlighting and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the characters of query appear in their order in a candidate symbol. Don't use prefix, substring, or similar strict matching.
These docs were added in response to this discussion, where somebody had very much the same issue as you.
Having a brief look at VSCode sources, internally it seems to use filters.matchFuzzy2() for the highlighting (see here and here). I don't think it's exposed in the API, so you would probably have to copy it if you wanted the behavior to match exactly.

How can i tell specman to terminate the test after 5 dut_erros

I need to specify to specman a maximal amount of dut_errors in the test, which after that limit the test should be terminated.
Currently i have the option to terminate the test when an error accord or never.
You can also change the check_effect to ERROR, so it will cause the run to stop. For example (I am taking here Thorsten's example, and modify it):
extend sn_util {
!count_errors: uint;
};
extend dut_error_struct {
pre_error() is also {
util.count_errors += 1;
if util.count_errors > 5 {
set_check_effect(ERROR);
};
};
};
AFAIK this does not work out of the box. You could count the errors by using a global variable and extending the error struct, something in the line of
extend sn_util {
!count_errors: uint;
count() is {
count_errors += 1;
if count_errors > 5 { stop_run() };
};
};
extend dut_error_struct {
write() is also { util.count() };
};
There might even be an object in global that does the counting already, but probably not documented.

In Cocos2d is it possible to use multiple tags for a single object?

I want to be able to identify a group of objects for a CCSpriteBatchNode, but also identify a sub group of that group. To do something similar to this
CCArray *listOfGameObjects = [sceneSpriteBatchNode children];
for (GameObject *tempObject in listOfGameObjects) {
if ([tempObject tag] == kBottleTagValue) {
//make bottle yellow
if ([tempObject tag] == kBrokenBottleTagValue) {
//also make bottle smaller
}
}
}
In the example all bottles would be turned yellow, and if the bottle was also tagged as broken it would be made smaller. So the broken bottle would need to be tagged with kBottleTagValue and kBrokenBottleTagValue. Is there away to do this? cause when I try to just add two tags it fails.
Yes you can do that using bit masking.
For example define your tag like that:
enum
{
kBottleTagValue = 1 << 0;
kBrokenBottleTagValue = 1 << 1;
};
Then tag your sprite:
[yoursprite setTag:kBottleTagValue|kBrokenBottleTagValue];
To finish you can check if your sprite is a broken bottles by doing something like that:
CCArray *listOfGameObjects = [sceneSpriteBatchNode children];
for (GameObject *tempObject in listOfGameObjects)
{
if ([tempObject tag] & kBottleTagValue)
{
//make bottle yellow
if ([tempObject tag] & kBrokenBottleTagValue)
{
//also make bottle smaller
}
}
}
I hope it'll help you.
Using bitmasking is overkill and there's no need to abuse the tag property.
Speaking of properties: You can add a boolean property to your class and use if ([tempObject isClass:[BottleClass class]]) for the first logic gate.
I don't actually know Cocos2d but based on a quick reading, I guess you've descended GameObject, by whatever roundabout route, from CCNode? In that case the tag field is an integer. You can't store multiple values to it, but you could use it as a bit field. For example:
#define kTagValueBottle 0x0001
#define kTagValueBroken 0x0002
#define kTagValueAnotherAttribute 0x0004
#define kTagValueAThirdAttribute 0x0008
#define kTagValueAFourthAttribute 0x0010
/* etc */
You'd then assign the type as, for example:
object.tag = kTagValueBottle | kTagValueBroken;
So that computes the bitwise OR of kTagValueBottle and kTagValueBroken, and stores it as the new tag. You could also add a property at any time using a bitwise OR:
object.tag |= kTagValueBroken;
Or remove by using a bitwise AND with the inverse mask:
object.tag &= ~kTagValueBroken;
You'd replace your direct comparison tests with testing individual bits via a bitwise AND:
// if ([tempObject tag] == kBottleTagValue) // old test
if ([tempObject tag] & kBottleTagValue) // new test
This is the same sort of system that Apple use for properties like autoresizingFlags on UIView.
If you can handle reading example code in PHP rather than Objective-C, this seemed to be the most helpful article that I could find quickly through Google, though admittedly from slender pickings.

How to know if a float got a decimals

I'm building a simple calculator for a classroom, this is the code to show the result:
- (void)doTheMathForPlus:(float)val {
float conto = self.contBox + val;
self.myDisplay.text = [NSString stringWithFormat:#"%.02f", conto];
}
I need to know if "conto" have decimals (to change the format of the string in a if statement)
how to do it?
thanks
if (conto == (int)conto) {
}
Hope this helps.
you'd better wrap that with #define and put this line in your .pch file
#define HAS_DECIMALS(x) (x!=(int)x)
than use anywhere in the code:
if (HAS_DECIMALS(conto)) {
//number has decimals
} else {
//number does not have decimals
}
Yes, dredful is right with his answer.
And, You also can use different functions like floor, ceil, round. In You case better "floor(conto)".
But, you can't do like Kyr Dunenkoff suggested. becouse, all operands for"%" should be integer, but not float as "conto".

Pass a block of code?

Is it possible to pass a block of code, for example:
int i = 0;
while (i < [array count]) {
//Code to pass in here
i++;
}
Reason being that i need to perform various actions on every item in an array at different times, it'd be nice to have 1 method and pass it a block of code to run.
Have you considered using blocks. It's just an idea and not working or compilable code
typedef int (^block_t)();
-(void) methodName:(block_t) code_block
{
int i = 0;
while (i < [array count]) {
code_block() //Code to pass in here
i++;
}
block_t youCode = ^{ NSLog("Just an example"); }
[self methodName:youCode];
You can definitely iterate an array and process a block of code on it. This feature has been a standard part of Objective C since 2.0, iOS since 4.0 and in addition was included in Snow Leopard. If you look up the NSArray class reference you will find the following functions:
enumerateObjectsAtIndexes:options:usingBlock:
Executes a given block using the
objects in the array at the specified
indexes.
enumerateObjectsUsingBlock: Executes a
given block using each object in the
array, starting with the first object
and continuing through the array to
the last object.
enumerateObjectsWithOptions:usingBlock:
Executes a given block using each
object in the array.
You can define the code block to be executed globally in your implementation file, or in place where its needed. You can find some good examples on block programming here: http://thirdcog.eu/pwcblocks/.
It sounds like you want "blocks", which are a feature of Objective-C similar to "lambdas", "anonymous functions" and "closures" in other languages.
See Apple's documentation: Blocks Programming Topics
You should put the code into a method and call the method like so:
-(void)foo{
int i = 0;
while (i < [array count]) {
[self myMethod];
i++;
}
}
-(void)myMethod{
//Code to pass in here
}
You could also store the method as a variable allowing you to change which method is called
SEL methodToCall = #selector(myMethod);
-(void)foo{
int i = 0;
while (i < [array count]){
[self performSelector:methodToCall];
i++;
}
}
-(void)myMethod{
//Code to pass in here
}
first of all you could give a more detailed example.
second you could take a look at Action or Func in case you need a return message (well something equivalent for obj-C if exists)
but again, not understanding what you need to do, it is hard to give you an answer
cause from you Q i could understand as #Trevor did that you need to run a method:
int i = 0;
while (i < [array count]) {
if (i % 2)
EvenMethod(array[i])
else
OddMethod(array[i])
i++;
}
If you can live with 4.0+ compatibility, I highly recommend the use of blocks.
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
gives you all you need and you can define your block right where you need it. There are some other variants of this, too. Please refer to the 'NSArray' documentation.
Why not just define functions that do what you want, and call them at various times with the items in your array as arguments?
If your concern is that you don't want redundant code with multiple while loops you have here, you could write a function that takes an array and a function as an argument, then applies that function to every element in the array.
Adapted from here:
//------------------------------------------------------------------------------------
// 2.6 How to Pass a Function Pointer
// <pt2Func> is a pointer to a function which returns void and takes an NSObject*
void DoForAllItems( NSArray* array, void (*pt2Func)(NSObject*) )
{
int i = 0;
while (i < [array count]) {
(*pt2Func)([array objectAtIndex:i]);
i++;
}
}
// 'DoIt' takes an NSObject*
void DoIt (NSObject* object){ NSLog(#"DoIt"); }
// execute example code
void Pass_A_Function_Pointer()
{
NSArray* array= [NSArray arrayWithObjects:#"1", #"2", nil];
DoForAllItems(array, &DoIt);
}
http://thirdcog.eu/pwcblocks/#objcblocks
Blocks were added recently to Objective-C I hope they have found their way to the Iphone also.
and it was anwered here also before:
Using Objective-C Blocks
Regards
If you are using Objective C++, I would strongly recommend function objects (even over blocks). They have a nice syntax, are easy to use, and are supported everywhere on modern C++ compilers (MSVC++11, GNUC++11, and LLVMC++11):
void go( function<void (int arg)> func )
{
int i = 0;
while (i < [array count]) {
//Code to pass in here
func( i ) ; // runs func on i
i++;
}
}
calling it:
go( []( int arg ){ // the square brackets are the "capture"
printf( "arg was %d\n", arg ) ; // arg takes on whatever value was passed to it,
// just like a normal C function
} ) ;