Both _pegHoleImage and _isPeg are private class variables yet _isPeg is seen by other functions but _pegHoleImage is not. What is the difference? I get the error message in Android studio that _pegHoleImage is not used, but I use it in the setImage() function. Thanks in advance for your help.
class PegHole {
PegHole({#required isPeg}) {
_isPeg = isPeg;
setImage();
}
Image _pegHoleImage;
bool _isPeg;
toggle() {
_isPeg = !_isPeg;
setImage();
}
setImage() {
_pegHoleImage = _isPeg ? Image.asset(kPEG_FILENAME) : Image.asset(kHOLE_FILENAME);
}
bool getPegStatus() {
return _isPeg;
}
}
It's because you're setting it but never using it.
Add this getter and it goes away.
Image get pegHoleImage => _pegHoleImage;
Related
I need to observe a LiveData object from a data class. I have observed these two methods are working:
Method 1: Convert the class to a LifecycleOwner
class MyObservingClass: LifecycleOwner {
private val lifecycleRegistry: LifecycleRegistry
var receivedData: String = ""
init {
lifecycleRegistry = LifecycleRegistry(this)
Server.dataObject.observe(this) {
receivedData = it
Log.d(DEBUG_TAG, "observed : $it")
}
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
Method 2: Use observeForever
class MyObservingClass {
var receivedData: String = ""
init {
Server.dataObject.observeForever {
receivedData = it
Log.d(DEBUG_TAG, "observed : $it")
}
}
}
Then I am using it as val obj = MyObservingClass() in some other place. As previously stated both of these approaches are working and I can observe the LiveData.
My question is, will these two methods prevent garbage collection of the objects as they are observing indefinitely? Are both these methods flawed? I am making an Android library and don't have life-cycle aware components like Activity.
Thanks for the replies :)
I am little new to dart. I am trying to understand the difference between these two methods. Are both methods different or same? Where should I use one above another? Can someone explain it to me?
class A {
A.executor1() {
print('executor one is called');
}
static executor2() {
print('executor two is called');
}
}
Meanwhile neither of the method call is required to make a new instance? both are called using the class name.
void main() {
A.executor1(); // Will print "executor one is called"
A.executor2(); // Will print "executor two is called"
}
A.executor1() is a named constructor. static executor2() is a static method.
With an IDE (or dartpad.dev) you can see the different return types when you are placing the cursor over each method:
void main() {
A.executor1(); // (new) A A.executor1()
A.executor2(); // dynamic executor2()
}
static methods can be called without creating an instance of the class. executor1 will have access to this and so on because it's attached to an actual instance, but static methods will not because they aren't attached to anything.
Consider (in Javascript):
class Bicycle {
static numWheels = 2;
constructor(color) {
this.color = color;
}
static numberOfWheels() {
console.log(`Every bike has ${this.numWheels} wheels.`);
}
myColor() {
console.log(`This bike is ${this.color}.`);
}
}
// property of an instance
new Bicycle('red').myColor();
// available for anyone!
Bicycle.numberOfWheels();
I stuck into an issue where I want to declare a property in NSError extension.
This is my error structure
struct CustomError {
var errorTitle: String?
var errorDescription: String?
var isClear: Bool?
}
This is my extension
extension NSError {
var customeError:CustomError {
get {
return self.customeError
}
set {
self.customeError = newValue
}
}
}
I am getting bad access error while setting custom error into the property.
You cannot add properties to extensions.
There only way to make it work is to use objc_getAssociatedObject to have stored properties.
After searching this issue over the internet I found a cool solution. We can declare but there is the trick here is the updated extension.
extension NSError {
struct Holder {
static var customErr: CustomError = CustomError()
}
var customeError:CustomError {
get {
return Holder.customErr
}
set {
Holder.customErr = newValue
}
}
}
Actually previously in the question which I posted there was retain cycle but when I added holder then there is no cycle and code working perfectly.
Thanks, guys
In my project I am having an issue with Swift, that it doesn't recognize variables containing protocol types. This means I can't use a variable that stores a type, to check if the type of an instance matches it.
I attached problematic part of the code with some brief context.
Is this some kind of bug or am I overseeing something really badly?
Using XCode 7.3, Swift 2.2
//Context of Issue BEGIN
class TaskValueObject {
//ManyData, VeryComplexity, SoBig, wow..
}
typealias TaskListSorterBlock = (TaskValueObject, TaskValueObject) -> Bool
protocol TaskListSorter : class {
init()
var localizedTitle : String { get }
var sorterBlock : TaskListSorterBlock { get }
}
class PriorityTaskListSorter : TaskListSorter {
// ... Implementation ...
}
// Many other TaskListSorter implementation classes ...
//Context of Issue END
class TaskListContainer {
weak var currentSorter : TaskListSorter?
var sorters : [TaskListSorter]
init() {
self.sorters = [ PriorityTaskListSorter(), /* ... Instances created for <TaskListSorter> implementing class ... */ ]
loadDefaultSorter()
}
static var defaultSorterType : TaskListSorter.Type = PriorityTaskListSorter.self
private func loadDefaultSorter() {
let defaultSorterType = TaskListContainer.defaultSorterType
for sorter in self.sorters {
if sorter is defaultSorterType {
// ^ ERROR HERE : defaultSorterType is not a 'type'
self.currentSorter = sorter
}
}
}
}
Update 1: I get the same error if I replace the problematic line with the following:
if let defaultSorter = sorter as? defaultSorterType {
Update 2: Replacing the problematic line with the one below, makes the code work. However I am using here the 'dynamicType' which is not offered by code completion (must be a reason for that...). Also the question remains, why the first 2 attempts didn't work?
if sorter.dynamicType == defaultSorterType {
I have a function that gets and parses data from Firebase. I have a validation "parseUserModel) that returns "Bool" type if the model meets the requirements to pass. I set this value to validUser which is of Bool type. The model I'm pulling actually passes and returns a boolean of true.
Here's where the issue happens.
If(validUser) { ... code ... } fails even though the validUser is "true".
I've played around with the actual return type and I've tried these things:
validUser.boolValue and setting this inside the if(validUser.boolValue)
this fails
setting the if(validUser) { ... code ... }
this fails
setting the if(validUser == true) {..code..}
this fails
setting the if(validUser.boolValue == true) {code}
this fails
I'm all out of ideas as to why exactly this is failing. I'm comparing a primitive type (I'm assuming) to another primitive type.
My Questions
is the 'true' keyword in Swift not actually a Bool object type?
why is this failing when I'm explicitly asking for the boolValue?
is their a Swift bug I should know about?
is the if statement not doing what I think it should be doing?
Retrieve Data Function
public static func retrieveUserData(user:UserModel, completion:(success:Bool)->Void){
if(user.username != nil){
let fbRef = Firebase(url: GlobalVariables().FB_BASE_URL+"users/\(user.username)")
fbRef.observeSingleEventOfType(FEventType.Value, withBlock: { (snapshot) -> Void in
if(snapshot.value != nil){
let validUser:Bool = UserModel.sharedInstance.parseUserData(JSON(snapshot.value))
println(validUser)
println(validUser.boolValue)
if(validUser.boolValue){
completion(success: true)
} else {
completion(success: false)
}
}
})
}
}
Parse Model and Validate
public func parseUserData(data:JSON) -> Bool {
var uName:String!
var uFullName:String!
if let username = data["username"].string {
UserModel.sharedInstance.username = username
}
if let fullName = data["fullName"].string {
UserModel.sharedInstance.fullName = fullName
} else {
return false
}
if let biography = data["biography"].string {
UserModel.sharedInstance.biography = biography
}
if let email = data["email"].string {
UserModel.sharedInstance.email = email
}
if let plistID = data["playlistCollectionID"].string {
UserModel.sharedInstance.playlistCollectionID = plistID
} else {
//generate a playlistCollectionID because the user doesn't have one
UserModel.sharedInstance.playlistCollectionID = NSUUID().UUIDString
}
if(UserModel.validateUserObject(UserModel.sharedInstance)) {
return true
} else {
return false
}
}
Println() log from Xcode
true
true
the above two true are coming from the retrieval code
println(validUser) and println(validUser.boolValue)
The Bool type in Swift conforms to BooleanType, which has the member:
var boolValue: Bool { get }
The value stored in validUser is definitely a Bool, because otherwise you wouldn't be able to put it in a variable of the Bool type.
The most likely situation here is that there is a bug in your code. Go over it again and make sure that it's actually entering the else block instead of the if block.
As a side note, the Swift formatting convention for if statements looks like this:
if condition {
...
} else {
...
}
as opposed to if(condition){...
Due to my own idiocy I was sending the shared user instance UserModel into itself.
private static func validateUserObject(object:UserModel) -> Bool {
println(object.username)
println(object.fullName)
if(object.username != nil && object.fullName != nil){
return true
} else {
return false
}
}
So I would call the method like this...
UserModel.sharedInstance.validateUserObject(self)
This would cause the Function specialization explosion. This would not crash the app (which is the strange part). It would continue and return the true boolean (because the model was valid).